diff options
Diffstat (limited to 'tests/auto')
115 files changed, 3602 insertions, 1659 deletions
diff --git a/tests/auto/cmake/CMakeLists.txt b/tests/auto/cmake/CMakeLists.txt index c780096854..0e6da23c09 100644 --- a/tests/auto/cmake/CMakeLists.txt +++ b/tests/auto/cmake/CMakeLists.txt @@ -97,6 +97,7 @@ if (NOT WIN32 OR (WIN32 AND NOT CMAKE_VERSION VERSION_LESS 2.8.11)) expect_pass(test_add_binary_resources_delayed_file BINARY test_add_binary_resources_delayed_file) endif() expect_pass(test_private_includes) +expect_pass(test_private_targets) expect_pass(test_testlib_definitions) expect_pass(test_json_plugin_includes) diff --git a/tests/auto/cmake/test_private_targets/CMakeLists.txt b/tests/auto/cmake/test_private_targets/CMakeLists.txt new file mode 100644 index 0000000000..f7f3902869 --- /dev/null +++ b/tests/auto/cmake/test_private_targets/CMakeLists.txt @@ -0,0 +1,9 @@ + +cmake_minimum_required(VERSION 3.0) + +project(test_private_targets) + +find_package(Qt5Gui REQUIRED) + +add_executable(testapp main.cpp) +target_link_libraries(testapp Qt5::GuiPrivate) diff --git a/tests/auto/other/atwrapper/atWrapperAutotest.cpp b/tests/auto/cmake/test_private_targets/main.cpp index ea40cc92b9..40dc4c243c 100644 --- a/tests/auto/other/atwrapper/atWrapperAutotest.cpp +++ b/tests/auto/cmake/test_private_targets/main.cpp @@ -1,6 +1,6 @@ /**************************************************************************** ** -** Copyright (C) 2016 The Qt Company Ltd. +** Copyright (C) 2016 Stephen Kelly <steveire@gmail.com> ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. @@ -26,40 +26,28 @@ ** ****************************************************************************/ +#include <QGuiApplication> -#include <QtTest/QtTest> -#include "atWrapper.h" -#include <QApplication> +#include <private/qwindow_p.h> +#include <private/qobject_p.h> +#include <QtGui/private/qwindow_p.h> +#include <QtCore/private/qobject_p.h> -class atWrapperAutotest: public QObject +int main(int argc, char **argv) { + QGuiApplication app(argc, argv); -Q_OBJECT + QWindow window; -public slots: - void init(); + auto windowPrivate = QWindowPrivate::get(&window); -private slots: - void runTest(); -}; + if (windowPrivate->visible) + return 1; -void atWrapperAutotest::init() -{ -#ifndef Q_OS_IRIX - QDir::setCurrent(SRCDIR); -#endif -} + auto objectPrivate = QObjectPrivate::get(&window); -void atWrapperAutotest::runTest() -{ + auto mo = window.metaObject(); - //QApplication app(argc, argv); - - atWrapper wrapper; - if (!wrapper.runAutoTests()) - QSKIP("Arthur not tested on this machine"); - QVERIFY(true); + // Should be 0 + return objectPrivate->signalIndex("destroyed()", &mo); } - -QTEST_MAIN(atWrapperAutotest) -#include "atWrapperAutotest.moc" diff --git a/tests/auto/corelib/animation/qparallelanimationgroup/tst_qparallelanimationgroup.cpp b/tests/auto/corelib/animation/qparallelanimationgroup/tst_qparallelanimationgroup.cpp index a8d64f1cd9..18a6268ec0 100644 --- a/tests/auto/corelib/animation/qparallelanimationgroup/tst_qparallelanimationgroup.cpp +++ b/tests/auto/corelib/animation/qparallelanimationgroup/tst_qparallelanimationgroup.cpp @@ -786,6 +786,9 @@ struct AnimState { int time; int state; }; +QT_BEGIN_NAMESPACE +Q_DECLARE_TYPEINFO(AnimState, Q_MOVABLE_TYPE); +QT_END_NAMESPACE #define Running QAbstractAnimation::Running #define Stopped QAbstractAnimation::Stopped diff --git a/tests/auto/corelib/animation/qpropertyanimation/tst_qpropertyanimation.cpp b/tests/auto/corelib/animation/qpropertyanimation/tst_qpropertyanimation.cpp index b0b0a307e9..cf4c4e1bdb 100644 --- a/tests/auto/corelib/animation/qpropertyanimation/tst_qpropertyanimation.cpp +++ b/tests/auto/corelib/animation/qpropertyanimation/tst_qpropertyanimation.cpp @@ -427,7 +427,7 @@ public: void setOle(int v) { o = v; values << v; } int o; - QList<int> values; + QVector<int> values; }; void tst_QPropertyAnimation::noStartValue() @@ -672,19 +672,15 @@ struct Number Number(int n) : n(n) {} - Number(const Number &other) - : n(other.n){} - - Number &operator=(const Number &other) { - n = other.n; - return *this; - } bool operator==(const Number &other) const { return n == other.n; } int n; }; +QT_BEGIN_NAMESPACE +Q_DECLARE_TYPEINFO(Number, Q_PRIMITIVE_TYPE); +QT_END_NAMESPACE Q_DECLARE_METATYPE(Number) diff --git a/tests/auto/corelib/animation/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp b/tests/auto/corelib/animation/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp index 6d66f05835..06e9fe7a66 100644 --- a/tests/auto/corelib/animation/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp +++ b/tests/auto/corelib/animation/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp @@ -563,7 +563,7 @@ void tst_QSequentialAnimationGroup::seekingBackwards() QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); } -typedef QList<QAbstractAnimation::State> StateList; +typedef QVector<QAbstractAnimation::State> StateList; static bool compareStates(const QSignalSpy& spy, const StateList &expectedStates) { diff --git a/tests/auto/corelib/global/qflags/tst_qflags.cpp b/tests/auto/corelib/global/qflags/tst_qflags.cpp index 634d9a2df3..d70b099fe3 100644 --- a/tests/auto/corelib/global/qflags/tst_qflags.cpp +++ b/tests/auto/corelib/global/qflags/tst_qflags.cpp @@ -134,11 +134,11 @@ void tst_QFlags::signedness() // underlying type is implementation-defined, we need to allow for // a different signedness, so we only check that the relative // signedness of the types matches: - Q_STATIC_ASSERT((QtPrivate::QIsUnsignedEnum<Qt::MouseButton>::value == - QtPrivate::QIsUnsignedEnum<Qt::MouseButtons::Int>::value)); + Q_STATIC_ASSERT((std::is_unsigned<typename std::underlying_type<Qt::MouseButton>::type>::value == + std::is_unsigned<Qt::MouseButtons::Int>::value)); - Q_STATIC_ASSERT((QtPrivate::QIsSignedEnum<Qt::AlignmentFlag>::value == - QtPrivate::QIsSignedEnum<Qt::Alignment::Int>::value)); + Q_STATIC_ASSERT((std::is_signed<typename std::underlying_type<Qt::AlignmentFlag>::type>::value == + std::is_signed<Qt::Alignment::Int>::value)); } #if defined(Q_COMPILER_CLASS_ENUM) diff --git a/tests/auto/corelib/global/qgetputenv/tst_qgetputenv.cpp b/tests/auto/corelib/global/qgetputenv/tst_qgetputenv.cpp index 7ffb5d0fd7..66fc578d5f 100644 --- a/tests/auto/corelib/global/qgetputenv/tst_qgetputenv.cpp +++ b/tests/auto/corelib/global/qgetputenv/tst_qgetputenv.cpp @@ -112,13 +112,13 @@ void tst_QGetPutEnv::intValue_data() ROW(0xffffffff, 0, false); const int bases[] = {10, 8, 16}; for (size_t i = 0; i < sizeof bases / sizeof *bases; ++i) { - QTest::newRow(qPrintable(QString::asprintf("INT_MAX, base %d", bases[i]))) + QTest::addRow("INT_MAX, base %d", bases[i]) << QByteArray::number(INT_MAX) << INT_MAX << true; - QTest::newRow(qPrintable(QString::asprintf("INT_MAX+1, base %d", bases[i]))) + QTest::addRow("INT_MAX+1, base %d", bases[i]) << QByteArray::number(qlonglong(INT_MAX) + 1) << 0 << false; - QTest::newRow(qPrintable(QString::asprintf("INT_MIN, base %d", bases[i]))) + QTest::addRow("INT_MIN, base %d", bases[i]) << QByteArray::number(INT_MIN) << INT_MIN << true; - QTest::newRow(qPrintable(QString::asprintf("INT_MIN-1, base %d", bases[i]))) + QTest::addRow("INT_MIN-1, base %d", bases[i]) << QByteArray::number(qlonglong(INT_MIN) - 1) << 0 << false; }; } diff --git a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp index bb6ec1c8e7..083526fdc4 100644 --- a/tests/auto/corelib/global/qglobal/tst_qglobal.cpp +++ b/tests/auto/corelib/global/qglobal/tst_qglobal.cpp @@ -102,6 +102,13 @@ void tst_QGlobal::for_each() QCOMPARE(i, counter++); } QCOMPARE(counter, list.count()); + + // check whether we can use a lambda + counter = 0; + foreach (int i, [&](){ return list; }()) { + QCOMPARE(i, counter++); + } + QCOMPARE(counter, list.count()); } void tst_QGlobal::qassert() diff --git a/tests/auto/corelib/global/qglobalstatic/qglobalstatic.pro b/tests/auto/corelib/global/qglobalstatic/qglobalstatic.pro index 056d940da7..21bb040b8d 100644 --- a/tests/auto/corelib/global/qglobalstatic/qglobalstatic.pro +++ b/tests/auto/corelib/global/qglobalstatic/qglobalstatic.pro @@ -5,7 +5,6 @@ QT -= gui TARGET = tst_qglobalstatic CONFIG += console -CONFIG -= app_bundle CONFIG += exceptions SOURCES += tst_qglobalstatic.cpp diff --git a/tests/auto/corelib/global/qlogging/test/test.pro b/tests/auto/corelib/global/qlogging/test/test.pro index 93eee7307a..7c46ae9d16 100644 --- a/tests/auto/corelib/global/qlogging/test/test.pro +++ b/tests/auto/corelib/global/qlogging/test/test.pro @@ -1,5 +1,5 @@ CONFIG += testcase -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target qtConfig(c++11): CONFIG += c++11 qtConfig(c++14): CONFIG += c++14 TARGET = ../tst_qlogging diff --git a/tests/auto/corelib/io/io.pro b/tests/auto/corelib/io/io.pro index 0542833456..c37c060acd 100644 --- a/tests/auto/corelib/io/io.pro +++ b/tests/auto/corelib/io/io.pro @@ -11,6 +11,7 @@ SUBDIRS=\ largefile \ qfileinfo \ qfileselector \ + qfilesystemmetadata \ qfilesystementry \ qfilesystemwatcher \ qiodevice \ @@ -59,9 +60,11 @@ SUBDIRS=\ win32:!qtConfig(private_tests): SUBDIRS -= \ qfilesystementry +!qtConfig(processenvironment): SUBDIRS -= \ + qprocessenvironment + winrt: SUBDIRS -= \ qprocess \ qprocess-noapplication \ - qprocessenvironment \ qstorageinfo \ qwinoverlappedionotifier diff --git a/tests/auto/corelib/io/qdir/tst_qdir.cpp b/tests/auto/corelib/io/qdir/tst_qdir.cpp index b86c6e4dfa..49ee8eb32c 100644 --- a/tests/auto/corelib/io/qdir/tst_qdir.cpp +++ b/tests/auto/corelib/io/qdir/tst_qdir.cpp @@ -211,6 +211,9 @@ private slots: void cdBelowRoot_data(); void cdBelowRoot(); + void emptyDir(); + void nonEmptyDir(); + private: #ifdef BUILTIN_TESTDATA QString m_dataPath; @@ -2281,6 +2284,26 @@ void tst_QDir::cdBelowRoot() QCOMPARE(dir.path(), rootPath); } +void tst_QDir::emptyDir() +{ + const QString tempDir = QDir::currentPath() + "/tmpdir/"; + QVERIFY(QDir().mkdir(tempDir)); + QVERIFY(QDir(tempDir).mkdir("emptyDirectory")); + + QDir testDir(tempDir + "emptyDirectory"); + QVERIFY(testDir.isEmpty()); + QVERIFY(!testDir.isEmpty(QDir::AllEntries)); + QVERIFY(!testDir.isEmpty(QDir::AllEntries | QDir::NoDot)); + QVERIFY(!testDir.isEmpty(QDir::AllEntries | QDir::NoDotDot)); + QVERIFY(QDir(tempDir).removeRecursively()); +} + +void tst_QDir::nonEmptyDir() +{ + const QDir dir(m_dataPath); + QVERIFY(!dir.isEmpty()); +} + QTEST_MAIN(tst_QDir) #include "tst_qdir.moc" diff --git a/tests/auto/corelib/io/qfile/test/test.pro b/tests/auto/corelib/io/qfile/test/test.pro index c0c4b9d5d2..5f1963cf5f 100644 --- a/tests/auto/corelib/io/qfile/test/test.pro +++ b/tests/auto/corelib/io/qfile/test/test.pro @@ -1,5 +1,5 @@ CONFIG += testcase -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target QT = core-private core testlib qtHaveModule(network): QT += network else: DEFINES += QT_NO_NETWORK diff --git a/tests/auto/corelib/io/qfile/tst_qfile.cpp b/tests/auto/corelib/io/qfile/tst_qfile.cpp index 2ef4c2c6a1..e2a0c80396 100644 --- a/tests/auto/corelib/io/qfile/tst_qfile.cpp +++ b/tests/auto/corelib/io/qfile/tst_qfile.cpp @@ -1371,10 +1371,8 @@ void tst_QFile::copyFallback() #ifdef Q_OS_WIN #include <objbase.h> -#ifndef Q_OS_WINPHONE #include <shlobj.h> #endif -#endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINRT) static QString getWorkingDirectoryForLink(const QString &linkFileName) diff --git a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp index e5ede1ad06..8c2886f337 100644 --- a/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp +++ b/tests/auto/corelib/io/qfileselector/tst_qfileselector.cpp @@ -138,7 +138,7 @@ void tst_QFileSelector::basicTest_data() << QString(":/extras/test2"); QTest::newRow("custom1-withselector-nobasefile") << QString(":/extras/test3") << (QStringList() << custom1) - << QString(":/extras/test3"); + << QString(":/extras/+custom1/test3"); QString custom2("custom2"); QString custom3("custom3"); diff --git a/tests/auto/corelib/io/qfilesystemmetadata/qfilesystemmetadata.pro b/tests/auto/corelib/io/qfilesystemmetadata/qfilesystemmetadata.pro new file mode 100644 index 0000000000..a7d50ece43 --- /dev/null +++ b/tests/auto/corelib/io/qfilesystemmetadata/qfilesystemmetadata.pro @@ -0,0 +1,4 @@ +CONFIG += testcase parallel_test +TARGET = tst_qfilesystemmetadata +QT = core-private testlib +SOURCES = tst_qfilesystemmetadata.cpp diff --git a/tests/auto/corelib/io/qfilesystemmetadata/tst_qfilesystemmetadata.cpp b/tests/auto/corelib/io/qfilesystemmetadata/tst_qfilesystemmetadata.cpp new file mode 100644 index 0000000000..d17dffe830 --- /dev/null +++ b/tests/auto/corelib/io/qfilesystemmetadata/tst_qfilesystemmetadata.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2017 The Qt Company Ltd. +** Contact: http://www.qt.io/licensing/ +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL3$ +** 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 http://www.qt.io/terms-conditions. For further +** information use the contact form at http://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPLv3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or later as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information to +** ensure the GNU General Public License version 2.0 requirements will be +** met: http://www.gnu.org/licenses/gpl-2.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include <QtTest/QtTest> +#include <QtCore/private/qfilesystemmetadata_p.h> + +class tst_QFileSystemMetaData : public QObject +{ + Q_OBJECT + +private slots: + void timeSinceEpoch(); +}; + +#if defined(QT_BUILD_INTERNAL) && defined(QT_SHARED) +#ifdef Q_OS_WIN +static FILETIME epochToFileTime(long seconds) +{ + const qint64 sec = 10000000; + // FILETIME is time in 1e-7s units since 1601's start: epoch is 1970's + // start, 369 years (of which 3*24 +69/4 = 89 were leap) later. + const qint64 offset = qint64(365 * 369 + 89) * 24 * 3600; + const qint64 convert = (offset + seconds) * sec; + FILETIME parts; + parts.dwHighDateTime = convert >> 32; + parts.dwLowDateTime = convert & 0xffffffff; + return parts; +} +#endif + +void tst_QFileSystemMetaData::timeSinceEpoch() +{ + // Regression test for QTBUG-48306, used to fail for TZ=Russia/Moscow + // Oct 22 2014 6:00 UTC; TZ=Russia/Moscow changed from +4 to +3 on Oct 26. + const long afterEpochUtc = 1413957600L; + QFileSystemMetaData meta; +#ifdef Q_OS_WIN + WIN32_FIND_DATA data; + memset(&data, 0, sizeof(data)); + data.dwFileAttributes = FILE_ATTRIBUTE_NORMAL; + /* data.ftLastAccessTime = data.ftLastWriteTime = */ + data.ftCreationTime = epochToFileTime(afterEpochUtc); + meta.fillFromFindData(data); +#else + QT_STATBUF data; + memset(&data, 0, sizeof(data)); + data.st_ctime = afterEpochUtc; + meta.fillFromStatBuf(data); +#endif + QCOMPARE(meta.creationTime().toUTC(), + QDateTime::fromMSecsSinceEpoch(afterEpochUtc * qint64(1000), Qt::UTC)); +} +#else // i.e. no Q_AUTOTEST_EXPORT +void tst_QFileSystemMetaData::timeSinceEpoch() +{ + QSKIP("QFileSystemMetaData methods aren't available to test"); +} +#endif +QTEST_MAIN(tst_QFileSystemMetaData) +#include <tst_qfilesystemmetadata.moc> diff --git a/tests/auto/corelib/io/qlockfile/tst_qlockfile.pro b/tests/auto/corelib/io/qlockfile/tst_qlockfile.pro index 7b83d5dbe8..7a304fe779 100644 --- a/tests/auto/corelib/io/qlockfile/tst_qlockfile.pro +++ b/tests/auto/corelib/io/qlockfile/tst_qlockfile.pro @@ -1,5 +1,4 @@ CONFIG += testcase -CONFIG -= app_bundle TARGET = tst_qlockfile SOURCES += tst_qlockfile.cpp diff --git a/tests/auto/corelib/io/qprocess-noapplication/qprocess-noapplication.pro b/tests/auto/corelib/io/qprocess-noapplication/qprocess-noapplication.pro index e46e7e1100..8e46320e0c 100644 --- a/tests/auto/corelib/io/qprocess-noapplication/qprocess-noapplication.pro +++ b/tests/auto/corelib/io/qprocess-noapplication/qprocess-noapplication.pro @@ -1,4 +1,4 @@ CONFIG += testcase -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target QT = core testlib SOURCES = tst_qprocessnoapplication.cpp diff --git a/tests/auto/corelib/io/qprocess/test/test.pro b/tests/auto/corelib/io/qprocess/test/test.pro index 96d105a4b4..7d6a7973dc 100644 --- a/tests/auto/corelib/io/qprocess/test/test.pro +++ b/tests/auto/corelib/io/qprocess/test/test.pro @@ -1,5 +1,5 @@ CONFIG += testcase -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target QT = core-private testlib network SOURCES = ../tst_qprocess.cpp diff --git a/tests/auto/corelib/io/qsettings/tst_qsettings.cpp b/tests/auto/corelib/io/qsettings/tst_qsettings.cpp index dadf4b612e..fcff13b416 100644 --- a/tests/auto/corelib/io/qsettings/tst_qsettings.cpp +++ b/tests/auto/corelib/io/qsettings/tst_qsettings.cpp @@ -183,6 +183,7 @@ private slots: void embeddedZeroByte_data(); void embeddedZeroByte(); + void testXdg(); private: void cleanupTestFiles(); @@ -3557,5 +3558,77 @@ void tst_QSettings::consistentRegistryStorage() } #endif +#if defined(QT_BUILD_INTERNAL) && defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN) && !defined(Q_OS_ANDROID) && !defined(QT_NO_STANDARDPATHS) +QT_BEGIN_NAMESPACE +extern void clearDefaultPaths(); +QT_END_NAMESPACE +#endif +void tst_QSettings::testXdg() +{ +#if defined(QT_BUILD_INTERNAL) && defined(Q_OS_UNIX) && !defined(Q_OS_DARWIN) && !defined(Q_OS_ANDROID) && !defined(QT_NO_STANDARDPATHS) + // Note: The XDG_CONFIG_DIRS test must be done before overriding the system path + // by QSettings::setPath/setSystemIniPath (used in cleanupTestFiles()). + clearDefaultPaths(); + + // Initialize the env. variable & populate testing files. + const QStringList config_dirs = { settingsPath("xdg_1st"), settingsPath("xdg_2nd"), settingsPath("xdg_3rd") }; + qputenv("XDG_CONFIG_DIRS", config_dirs.join(':').toUtf8()); + QList<QSettings *> xdg_orgs, xdg_apps; + for (const auto & dir : config_dirs) { + xdg_orgs << new QSettings{dir + "/software.org.conf", QSettings::NativeFormat}; + xdg_apps << new QSettings{dir + "/software.org/KillerAPP.conf", QSettings::NativeFormat}; + } + Q_ASSERT(config_dirs.size() == 3 && xdg_orgs.size() == 3 && xdg_apps.size() == 3); + for (int i = 0; i < 3; ++i) { + xdg_orgs[i]->setValue("all", QString{"all_org%1"}.arg(i)); + xdg_apps[i]->setValue("all", QString{"all_app%1"}.arg(i)); + xdg_orgs[i]->setValue("all_only_org", QString{"all_only_org%1"}.arg(i)); + xdg_apps[i]->setValue("all_only_app", QString{"all_only_app%1"}.arg(i)); + + if (i > 0) { + xdg_orgs[i]->setValue("from2nd", QString{"from2nd_org%1"}.arg(i)); + xdg_apps[i]->setValue("from2nd", QString{"from2nd_app%1"}.arg(i)); + xdg_orgs[i]->setValue("from2nd_only_org", QString{"from2nd_only_org%1"}.arg(i)); + xdg_apps[i]->setValue("from2nd_only_app", QString{"from2nd_only_app%1"}.arg(i)); + } + + if (i > 1) { + xdg_orgs[i]->setValue("from3rd", QString{"from3rd_org%1"}.arg(i)); + xdg_apps[i]->setValue("from3rd", QString{"from3rd_app%1"}.arg(i)); + xdg_orgs[i]->setValue("from3rd_only_org", QString{"from3rd_only_org%1"}.arg(i)); + xdg_apps[i]->setValue("from3rd_only_app", QString{"from3rd_only_app%1"}.arg(i)); + } + } + qDeleteAll(xdg_apps); + qDeleteAll(xdg_orgs); + + // Do the test. + QSettings app{QSettings::SystemScope, "software.org", "KillerAPP"}, org{QSettings::SystemScope, "software.org"}; + + QVERIFY(app.value("all").toString() == "all_app0"); + QVERIFY(org.value("all").toString() == "all_org0"); + QVERIFY(app.value("all_only_org").toString() == "all_only_org0"); + QVERIFY(org.value("all_only_org").toString() == "all_only_org0"); + QVERIFY(app.value("all_only_app").toString() == "all_only_app0"); + QVERIFY(org.value("all_only_app").toString() == QString{}); + + QVERIFY(app.value("from2nd").toString() == "from2nd_app1"); + QVERIFY(org.value("from2nd").toString() == "from2nd_org1"); + QVERIFY(app.value("from2nd_only_org").toString() == "from2nd_only_org1"); + QVERIFY(org.value("from2nd_only_org").toString() == "from2nd_only_org1"); + QVERIFY(app.value("from2nd_only_app").toString() == "from2nd_only_app1"); + QVERIFY(org.value("from2nd_only_app").toString() == QString{}); + + QVERIFY(app.value("from3rd").toString() == "from3rd_app2"); + QVERIFY(org.value("from3rd").toString() == "from3rd_org2"); + QVERIFY(app.value("from3rd_only_org").toString() == "from3rd_only_org2"); + QVERIFY(org.value("from3rd_only_org").toString() == "from3rd_only_org2"); + QVERIFY(app.value("from3rd_only_app").toString() == "from3rd_only_app2"); + QVERIFY(org.value("from3rd_only_app").toString() == QString{}); +#else + QSKIP("This test is performed in QT_BUILD_INTERNAL on Q_XDG_PLATFORM with use of standard paths only."); +#endif +} + QTEST_MAIN(tst_QSettings) #include "tst_qsettings.moc" diff --git a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp index a7a761a2da..0a00e00d83 100644 --- a/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp +++ b/tests/auto/corelib/io/qstandardpaths/tst_qstandardpaths.cpp @@ -385,7 +385,7 @@ void tst_qstandardpaths::testFindExecutable_data() QTest::newRow("win-cmd-nosuffix") << QString() << QString::fromLatin1("cmd") << cmdPath; - if (QSysInfo::windowsVersion() >= QSysInfo::WV_WINDOWS8) { + if (QOperatingSystemVersion::current() >= QOperatingSystemVersion::Windows8) { // The logo executable on Windows 8 is perfectly suited for testing that the // suffix mechanism is not thrown off by dots in the name. // Note: Requires disabling WOW64 redirection, see initTestCase() diff --git a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp index 487c13be94..758bbead84 100644 --- a/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp +++ b/tests/auto/corelib/io/qtemporarydir/tst_qtemporarydir.cpp @@ -57,6 +57,8 @@ private slots: void fileTemplate_data(); void getSetCheck(); void fileName(); + void filePath_data(); + void filePath(); void autoRemove(); void nonWritableCurrentDir(); void openOnRootDrives(); @@ -204,6 +206,29 @@ void tst_QTemporaryDir::fileName() QCOMPARE(absoluteFilePath, absoluteTempPath); } +void tst_QTemporaryDir::filePath_data() +{ + QTest::addColumn<QString>("templatePath"); + QTest::addColumn<QString>("fileName"); + + QTest::newRow("0") << QString() << "/tmpfile"; + QTest::newRow("1") << QString() << "tmpfile"; + QTest::newRow("2") << "XXXXX" << "tmpfile"; + QTest::newRow("3") << "YYYYY" << "subdir/file"; +} + +void tst_QTemporaryDir::filePath() +{ + QFETCH(QString, templatePath); + QFETCH(QString, fileName); + + QTemporaryDir dir(templatePath); + const QString filePath = dir.filePath(fileName); + const QString expectedFilePath = QDir::isAbsolutePath(fileName) ? + QString() : dir.path() + QLatin1Char('/') + fileName; + QCOMPARE(filePath, expectedFilePath); +} + void tst_QTemporaryDir::autoRemove() { // Test auto remove diff --git a/tests/auto/corelib/json/json.pro b/tests/auto/corelib/json/json.pro index 16c2ae2fb7..8fa17c5c38 100644 --- a/tests/auto/corelib/json/json.pro +++ b/tests/auto/corelib/json/json.pro @@ -1,6 +1,5 @@ TARGET = tst_json QT = core-private testlib -CONFIG -= app_bundle CONFIG += testcase !android:TESTDATA += bom.json test.json test.bjson test3.json test2.json diff --git a/tests/auto/corelib/kernel/qcoreapplication/Info.plist b/tests/auto/corelib/kernel/qcoreapplication/Info.plist new file mode 100644 index 0000000000..a2927358bc --- /dev/null +++ b/tests/auto/corelib/kernel/qcoreapplication/Info.plist @@ -0,0 +1,8 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> +<plist version="1.0"> +<dict> + <key>CFBundleVersion</key> + <string>1.2.3</string> +</dict> +</plist> diff --git a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro b/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro index d166351490..e37542be65 100644 --- a/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro +++ b/tests/auto/corelib/kernel/qcoreapplication/qcoreapplication.pro @@ -3,4 +3,7 @@ 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 +darwin: QMAKE_LFLAGS += -Wl,-sectcreate,__TEXT,__info_plist,$$shell_quote($$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 0691297497..a7c608ec2e 100644 --- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp +++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.cpp @@ -153,6 +153,41 @@ void tst_QCoreApplication::qAppName() QCOMPARE(QCoreApplication::applicationName(), QString()); } +void tst_QCoreApplication::qAppVersion() +{ +#if defined(Q_OS_WIN) + const char appVersion[] = "1.2.3.4"; +#elif defined(Q_OS_DARWIN) || defined(Q_OS_ANDROID) + const char appVersion[] = "1.2.3"; +#else + const char appVersion[] = ""; +#endif + + { + int argc = 0; + char *argv[] = { nullptr }; + TestApplication app(argc, argv); + QCOMPARE(QCoreApplication::applicationVersion(), QString::fromLatin1(appVersion)); + } + // The application version should still be available after destruction + QCOMPARE(QCoreApplication::applicationVersion(), QString::fromLatin1(appVersion)); + + // Setting the appversion before creating the application should work + const QString wantedAppVersion("0.0.1"); + { + int argc = 0; + char *argv[] = { nullptr }; + QCoreApplication::setApplicationVersion(wantedAppVersion); + TestApplication app(argc, argv); + QCOMPARE(QCoreApplication::applicationVersion(), wantedAppVersion); + } + QCOMPARE(QCoreApplication::applicationVersion(), wantedAppVersion); + + // Restore to initial value + QCoreApplication::setApplicationVersion(QString()); + QCOMPARE(QCoreApplication::applicationVersion(), QString()); +} + void tst_QCoreApplication::argc() { #if defined(Q_OS_WINRT) diff --git a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h index 7fb1bde459..342bd272a3 100644 --- a/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h +++ b/tests/auto/corelib/kernel/qcoreapplication/tst_qcoreapplication.h @@ -39,6 +39,7 @@ private slots: void sendEventsOnProcessEvents(); // this must be the first test void getSetCheck(); void qAppName(); + void qAppVersion(); void argc(); void postEvent(); void removePostedEvents(); diff --git a/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro b/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro index a42cd60236..9dfa29b0fc 100644 --- a/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro +++ b/tests/auto/corelib/kernel/qmetamethod/qmetamethod.pro @@ -2,4 +2,3 @@ CONFIG += testcase TARGET = tst_qmetamethod QT = core testlib SOURCES = tst_qmetamethod.cpp -mac:CONFIG -= app_bundle diff --git a/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro b/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro index f3153b3fd4..4da90c1096 100644 --- a/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro +++ b/tests/auto/corelib/kernel/qmetaobjectbuilder/qmetaobjectbuilder.pro @@ -2,4 +2,3 @@ CONFIG += testcase TARGET = tst_qmetaobjectbuilder QT = core-private testlib SOURCES = tst_qmetaobjectbuilder.cpp -mac:CONFIG -= app_bundle diff --git a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp index 7b75438b19..f44c40c27f 100644 --- a/tests/auto/corelib/kernel/qobject/tst_qobject.cpp +++ b/tests/auto/corelib/kernel/qobject/tst_qobject.cpp @@ -3402,14 +3402,12 @@ void tst_QObject::dumpObjectInfo() QObject a, b; QObject::connect(&a, SIGNAL(destroyed(QObject*)), &b, SLOT(deleteLater())); a.disconnect(&b); -#ifdef QT_DEBUG QTest::ignoreMessage(QtDebugMsg, "OBJECT QObject::unnamed"); QTest::ignoreMessage(QtDebugMsg, " SIGNALS OUT"); QTest::ignoreMessage(QtDebugMsg, " signal: destroyed(QObject*)"); QTest::ignoreMessage(QtDebugMsg, " <Disconnected receiver>"); QTest::ignoreMessage(QtDebugMsg, " SIGNALS IN"); QTest::ignoreMessage(QtDebugMsg, " <None>"); -#endif a.dumpObjectInfo(); // should not crash } diff --git a/tests/auto/corelib/kernel/qsharedmemory/test/test.pro b/tests/auto/corelib/kernel/qsharedmemory/test/test.pro index fabd2cf7a3..61124c27ee 100644 --- a/tests/auto/corelib/kernel/qsharedmemory/test/test.pro +++ b/tests/auto/corelib/kernel/qsharedmemory/test/test.pro @@ -2,7 +2,6 @@ CONFIG += testcase QT = core-private testlib -mac:CONFIG -= app_bundle linux:LIBS += -lrt SOURCES += tst_qsharedmemory.cpp diff --git a/tests/auto/corelib/kernel/qsystemsemaphore/test/test.pro b/tests/auto/corelib/kernel/qsystemsemaphore/test/test.pro index a0f63741d3..f60207eb01 100644 --- a/tests/auto/corelib/kernel/qsystemsemaphore/test/test.pro +++ b/tests/auto/corelib/kernel/qsystemsemaphore/test/test.pro @@ -2,7 +2,6 @@ CONFIG += testcase QT = core testlib win32: CONFIG += console -mac:CONFIG -= app_bundle SOURCES += tst_qsystemsemaphore.cpp TARGET = tst_qsystemsemaphore diff --git a/tests/auto/corelib/plugin/qfactoryloader/test/test.pro b/tests/auto/corelib/plugin/qfactoryloader/test/test.pro index 3345651730..9338f4ecc9 100644 --- a/tests/auto/corelib/plugin/qfactoryloader/test/test.pro +++ b/tests/auto/corelib/plugin/qfactoryloader/test/test.pro @@ -17,8 +17,6 @@ win32 { } } -mac: CONFIG -= app_bundle - !qtConfig(library) { LIBS += -L ../bin/ -lplugin1 -lplugin2 } diff --git a/tests/auto/corelib/plugin/qlibrary/tst/tst.pro b/tests/auto/corelib/plugin/qlibrary/tst/tst.pro index d59cd738bf..6e71ec8ff9 100644 --- a/tests/auto/corelib/plugin/qlibrary/tst/tst.pro +++ b/tests/auto/corelib/plugin/qlibrary/tst/tst.pro @@ -1,5 +1,4 @@ CONFIG += testcase -CONFIG -= app_bundle TARGET = ../tst_qlibrary QT = core testlib SOURCES = ../tst_qlibrary.cpp diff --git a/tests/auto/corelib/plugin/qpluginloader/machtest/machtest.pro b/tests/auto/corelib/plugin/qpluginloader/machtest/machtest.pro index e3d5bff5ff..7f7caa7f76 100644 --- a/tests/auto/corelib/plugin/qpluginloader/machtest/machtest.pro +++ b/tests/auto/corelib/plugin/qpluginloader/machtest/machtest.pro @@ -6,11 +6,16 @@ OTHER_FILES += \ # Needs explicit load()ing due to aux template. Relies on QT being non-empty. load(qt) +i386_d.target = good.i386.dylib +i386_d.depends = EXPORT_VALID_ARCHS=i386 i386.target = good.i386.dylib -i386.commands = $(CXX) $(CXXFLAGS) -shared -arch i386 -o $@ -I$(INCPATH) $< +i386.commands = $(CXX) $(CXXFLAGS) -shared -o $@ -I$(INCPATH) $< i386.depends += $$PWD/../fakeplugin.cpp + +x86_64_d.target = good.x86_64.dylib +x86_64_d.depends = EXPORT_VALID_ARCHS=x86_64 x86_64.target = good.x86_64.dylib -x86_64.commands = $(CXX) $(CXXFLAGS) -shared -arch x86_64 -o $@ -I$(INCPATH) $< +x86_64.commands = $(CXX) $(CXXFLAGS) -shared -o $@ -I$(INCPATH) $< x86_64.depends += $$PWD/../fakeplugin.cpp # Current Mac OS X toolchains have no compiler for PPC anymore @@ -49,7 +54,7 @@ bad.depends += $$PWD/generate-bad.pl MYTARGETS = $$fat_all.depends fat_all fat_no_x86_64 fat_no_i386 \ fat_stub_i386 fat_stub_x86_64 bad all.depends += $$MYTARGETS -QMAKE_EXTRA_TARGETS += $$MYTARGETS all +QMAKE_EXTRA_TARGETS += i386_d x86_64_d $$MYTARGETS all QMAKE_CLEAN += $$i386.target $$x86_64.target $$ppc64.target $$fat_all.target \ $$fat_no_i386.target $$fat_no_x86_64.target \ diff --git a/tests/auto/corelib/plugin/qpluginloader/tst/tst.pro b/tests/auto/corelib/plugin/qpluginloader/tst/tst.pro index 5f9fa6664b..c20e56ba4c 100644 --- a/tests/auto/corelib/plugin/qpluginloader/tst/tst.pro +++ b/tests/auto/corelib/plugin/qpluginloader/tst/tst.pro @@ -4,7 +4,6 @@ QT = core testlib qtConfig(private_tests): QT += core-private SOURCES = ../tst_qpluginloader.cpp ../fakeplugin.cpp HEADERS = ../theplugin/plugininterface.h -CONFIG -= app_bundle win32 { CONFIG(debug, debug|release) { diff --git a/tests/auto/corelib/thread/qmutex/tst_qmutex.cpp b/tests/auto/corelib/thread/qmutex/tst_qmutex.cpp index bf778e9fd1..e6c3a0cfd7 100644 --- a/tests/auto/corelib/thread/qmutex/tst_qmutex.cpp +++ b/tests/auto/corelib/thread/qmutex/tst_qmutex.cpp @@ -143,7 +143,7 @@ void tst_QMutex::convertToMilliseconds_data() auto add = [](TimeUnit unit, double d, long long i, qint64 expected) { const QScopedArrayPointer<char> enumName(QTest::toString(unit)); - QTest::newRow(qPrintable(QString::asprintf("%s:%f:%lld", enumName.data(), d, i))) + QTest::addRow("%s:%f:%lld", enumName.data(), d, i) << unit << d << qint64(i) << expected; }; diff --git a/tests/auto/corelib/thread/qsemaphore/BLACKLIST b/tests/auto/corelib/thread/qsemaphore/BLACKLIST deleted file mode 100644 index 9f6f6e3ba6..0000000000 --- a/tests/auto/corelib/thread/qsemaphore/BLACKLIST +++ /dev/null @@ -1,3 +0,0 @@ -# Times out randomly on linux, windows, osx -[tryAcquireWithTimeout] -* diff --git a/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp b/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp index 8597bf1a6d..f1eb32a282 100644 --- a/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp +++ b/tests/auto/corelib/thread/qsemaphore/tst_qsemaphore.cpp @@ -202,8 +202,8 @@ void tst_QSemaphore::tryAcquireWithTimeout_data() { QTest::addColumn<int>("timeout"); - QTest::newRow("1s") << 1000; - QTest::newRow("10s") << 10000; + QTest::newRow("0.2s") << 200; + QTest::newRow("2s") << 2000; } void tst_QSemaphore::tryAcquireWithTimeout() @@ -212,7 +212,7 @@ void tst_QSemaphore::tryAcquireWithTimeout() // timers are not guaranteed to be accurate down to the last millisecond, // so we permit the elapsed times to be up to this far from the expected value. - int fuzz = 50; + int fuzz = 50 + (timeout / 20); QSemaphore semaphore; QElapsedTimer time; diff --git a/tests/auto/corelib/thread/qthreadstorage/test/test.pro b/tests/auto/corelib/thread/qthreadstorage/test/test.pro index b9d661a9af..1a1fede186 100644 --- a/tests/auto/corelib/thread/qthreadstorage/test/test.pro +++ b/tests/auto/corelib/thread/qthreadstorage/test/test.pro @@ -1,6 +1,6 @@ CONFIG += testcase TARGET = ../tst_qthreadstorage -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target CONFIG += console QT = core testlib SOURCES = ../tst_qthreadstorage.cpp diff --git a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp index c14e9fadf7..e13c2894af 100644 --- a/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp +++ b/tests/auto/corelib/tools/qalgorithms/tst_qalgorithms.cpp @@ -1076,22 +1076,22 @@ void tst_QAlgorithms::popCount_data_impl(size_t sizeof_T_Int) const uint bits = bitsSetInByte(byte); const quint64 value = static_cast<quint64>(byte); const quint64 input = value << ((i % sizeof_T_Int) * 8U); - newRow(qPrintable(QString::asprintf("0x%016llx", input))) << input << bits; + QTest::addRow("0x%016llx", input) << input << bits; } // and some random ones: if (sizeof_T_Int >= 8) for (size_t i = 0; i < 1000; ++i) { const quint64 input = quint64(qrand()) << 32 | quint32(qrand()); - newRow(qPrintable(QString::asprintf("0x%016llx", input))) << input << bitsSetInInt64(input); + QTest::addRow("0x%016llx", input) << input << bitsSetInInt64(input); } else if (sizeof_T_Int >= 2) for (size_t i = 0; i < 1000 ; ++i) { const quint32 input = qrand(); if (sizeof_T_Int >= 4) - newRow(qPrintable(QString::asprintf("0x%08x", input))) << quint64(input) << bitsSetInInt(input); + QTest::addRow("0x%08x", input) << quint64(input) << bitsSetInInt(input); else - newRow(qPrintable(QString::asprintf("0x%04x", quint16(input & 0xFFFF)))) << quint64(input & 0xFFFF) << bitsSetInShort(input & 0xFFFF); + QTest::addRow("0x%04x", quint16(input & 0xFFFF)) << quint64(input & 0xFFFF) << bitsSetInShort(input & 0xFFFF); } } diff --git a/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp b/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp index 3be8379d29..ba2adddca0 100644 --- a/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp +++ b/tests/auto/corelib/tools/qarraydata/tst_qarraydata.cpp @@ -65,6 +65,8 @@ private slots: void simpleVectorReserve(); void allocate_data(); void allocate(); + void reallocate_data() { allocate_data(); } + void reallocate(); void alignment_data(); void alignment(); void typedData(); @@ -742,6 +744,54 @@ void tst_QArrayData::allocate() } } +void tst_QArrayData::reallocate() +{ + QFETCH(size_t, objectSize); + QFETCH(size_t, alignment); + QFETCH(QArrayData::AllocationOptions, allocateOptions); + QFETCH(bool, isCapacityReserved); + QFETCH(const QArrayData *, commonEmpty); + + // Maximum alignment that can be requested is that of QArrayData, + // otherwise, we can't use reallocate(). + Q_ASSERT(alignment <= Q_ALIGNOF(QArrayData)); + + // Minimum alignment that can be requested is that of QArrayData. + // Typically, this alignment is sizeof(void *) and ensured by malloc. + size_t minAlignment = qMax(alignment, Q_ALIGNOF(QArrayData)); + + int capacity = 10; + Deallocator keeper(objectSize, minAlignment); + QArrayData *data = QArrayData::allocate(objectSize, minAlignment, capacity, + QArrayData::AllocationOptions(allocateOptions) & ~QArrayData::Grow); + keeper.headers.append(data); + + memset(data->data(), 'A', objectSize * capacity); + data->size = capacity; + + // now try to reallocate + int newCapacity = 40; + data = QArrayData::reallocateUnaligned(data, objectSize, newCapacity, + QArrayData::AllocationOptions(allocateOptions)); + QVERIFY(data); + keeper.headers.clear(); + keeper.headers.append(data); + + QCOMPARE(data->size, capacity); + if (allocateOptions & QArrayData::Grow) + QVERIFY(data->alloc > uint(newCapacity)); + else + QCOMPARE(data->alloc, uint(newCapacity)); + QCOMPARE(data->capacityReserved, uint(isCapacityReserved)); +#if !defined(QT_NO_UNSHARABLE_CONTAINERS) + QFETCH(bool, isSharable); + QCOMPARE(data->ref.isSharable(), isSharable); +#endif + + for (int i = 0; i < capacity; ++i) + QCOMPARE(static_cast<char *>(data->data())[i], 'A'); +} + class Unaligned { char dummy[8]; diff --git a/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp b/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp index 310c5f6fd3..16a9c03351 100644 --- a/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp +++ b/tests/auto/corelib/tools/qbytearray/tst_qbytearray.cpp @@ -43,6 +43,8 @@ public: tst_QByteArray(); private slots: void swap(); + void qChecksum_data(); + void qChecksum(); void qCompress_data(); #ifndef QT_NO_COMPRESS void qCompress(); @@ -239,6 +241,34 @@ tst_QByteArray::tst_QByteArray() { } +void tst_QByteArray::qChecksum_data() +{ + QTest::addColumn<QByteArray>("data"); + QTest::addColumn<uint>("len"); + QTest::addColumn<Qt::ChecksumType>("standard"); + QTest::addColumn<uint>("checksum"); + + // Examples from ISO 14443-3 + QTest::newRow("1") << QByteArray("\x00\x00") << 2U << Qt::ChecksumItuV41 << 0x1EA0U; + QTest::newRow("2") << QByteArray("\x12\x34") << 2U << Qt::ChecksumItuV41 << 0xCF26U; + QTest::newRow("3") << QByteArray("\x00\x00\x00") << 3U << Qt::ChecksumIso3309 << 0xC6CCU; + QTest::newRow("4") << QByteArray("\x0F\xAA\xFF") << 3U << Qt::ChecksumIso3309 << 0xD1FCU; + QTest::newRow("5") << QByteArray("\x0A\x12\x34\x56") << 4U << Qt::ChecksumIso3309 << 0xF62CU; +} + +void tst_QByteArray::qChecksum() +{ + QFETCH(QByteArray, data); + QFETCH(uint, len); + QFETCH(Qt::ChecksumType, standard); + QFETCH(uint, checksum); + + if (standard == Qt::ChecksumIso3309) { + QCOMPARE(::qChecksum(data.constData(), len), static_cast<quint16>(checksum)); + } + QCOMPARE(::qChecksum(data.constData(), len, standard), static_cast<quint16>(checksum)); +} + void tst_QByteArray::qCompress_data() { QTest::addColumn<QByteArray>("ba"); @@ -1443,61 +1473,97 @@ void tst_QByteArray::appendAfterFromRawData() void tst_QByteArray::toFromHex_data() { QTest::addColumn<QByteArray>("str"); + QTest::addColumn<char>("sep"); QTest::addColumn<QByteArray>("hex"); QTest::addColumn<QByteArray>("hex_alt1"); - QTest::newRow("Qt is great!") + QTest::newRow("Qt is great! (default)") << QByteArray("Qt is great!") + << '\0' << QByteArray("517420697320677265617421") << QByteArray("51 74 20 69 73 20 67 72 65 61 74 21"); + QTest::newRow("Qt is great! (with space)") + << QByteArray("Qt is great!") + << ' ' + << QByteArray("51 74 20 69 73 20 67 72 65 61 74 21") + << QByteArray("51 74 20 69 73 20 67 72 65 61 74 21"); + + QTest::newRow("Qt is great! (with minus)") + << QByteArray("Qt is great!") + << '-' + << QByteArray("51-74-20-69-73-20-67-72-65-61-74-21") + << QByteArray("51-74-20-69-73-20-67-72-65-61-74-21"); + QTest::newRow("Qt is so great!") << QByteArray("Qt is so great!") + << '\0' << QByteArray("517420697320736f20677265617421") << QByteArray("51 74 20 69 73 20 73 6f 20 67 72 65 61 74 21"); QTest::newRow("default-constructed") << QByteArray() + << '\0' + << QByteArray() + << QByteArray(); + + QTest::newRow("default-constructed (with space)") + << QByteArray() + << ' ' << QByteArray() << QByteArray(); QTest::newRow("empty") << QByteArray("") + << '\0' + << QByteArray("") + << QByteArray(""); + + QTest::newRow("empty (with space)") + << QByteArray("") + << ' ' << QByteArray("") << QByteArray(""); QTest::newRow("array-of-null") << QByteArray("\0", 1) + << '\0' << QByteArray("00") << QByteArray("0"); QTest::newRow("no-leading-zero") << QByteArray("\xf") + << '\0' << QByteArray("0f") << QByteArray("f"); QTest::newRow("single-byte") << QByteArray("\xaf") + << '\0' << QByteArray("af") << QByteArray("xaf"); QTest::newRow("no-leading-zero") << QByteArray("\xd\xde\xad\xc0\xde") + << '\0' << QByteArray("0ddeadc0de") << QByteArray("ddeadc0de"); QTest::newRow("garbage") << QByteArray("\xC\xde\xeC\xea\xee\xDe\xee\xee") + << '\0' << QByteArray("0cdeeceaeedeeeee") << QByteArray("Code less. Create more. Deploy everywhere."); QTest::newRow("under-defined-1") << QByteArray("\x1\x23") + << '\0' << QByteArray("0123") << QByteArray("x123"); QTest::newRow("under-defined-2") << QByteArray("\x12\x34") + << '\0' << QByteArray("1234") << QByteArray("x1234"); } @@ -1505,16 +1571,23 @@ void tst_QByteArray::toFromHex_data() void tst_QByteArray::toFromHex() { QFETCH(QByteArray, str); + QFETCH(char, sep); QFETCH(QByteArray, hex); QFETCH(QByteArray, hex_alt1); - { + if (sep == 0) { const QByteArray th = str.toHex(); QCOMPARE(th.size(), hex.size()); QCOMPARE(th, hex); } { + const QByteArray th = str.toHex(sep); + QCOMPARE(th.size(), hex.size()); + QCOMPARE(th, hex); + } + + { const QByteArray fh = QByteArray::fromHex(hex); QCOMPARE(fh.size(), str.size()); QCOMPARE(fh, str); diff --git a/tests/auto/corelib/tools/qbytearraymatcher/qbytearraymatcher.pro b/tests/auto/corelib/tools/qbytearraymatcher/qbytearraymatcher.pro index 0624e1886c..9d4d5964c9 100644 --- a/tests/auto/corelib/tools/qbytearraymatcher/qbytearraymatcher.pro +++ b/tests/auto/corelib/tools/qbytearraymatcher/qbytearraymatcher.pro @@ -2,3 +2,4 @@ CONFIG += testcase TARGET = tst_qbytearraymatcher QT = core testlib SOURCES = tst_qbytearraymatcher.cpp +contains(QT_CONFIG, c++14):CONFIG += c++14 diff --git a/tests/auto/corelib/tools/qbytearraymatcher/tst_qbytearraymatcher.cpp b/tests/auto/corelib/tools/qbytearraymatcher/tst_qbytearraymatcher.cpp index 82cc432d55..647a3ae379 100644 --- a/tests/auto/corelib/tools/qbytearraymatcher/tst_qbytearraymatcher.cpp +++ b/tests/auto/corelib/tools/qbytearraymatcher/tst_qbytearraymatcher.cpp @@ -43,10 +43,9 @@ class tst_QByteArrayMatcher : public QObject private slots: void interface(); void indexIn(); + void staticByteArrayMatcher(); }; -static QByteArrayMatcher matcher1; - void tst_QByteArrayMatcher::interface() { const char needle[] = "abc123"; @@ -56,6 +55,8 @@ void tst_QByteArrayMatcher::interface() haystack.insert(42, "abc123"); haystack.insert(84, "abc123"); + QByteArrayMatcher matcher1; + matcher1 = QByteArrayMatcher(QByteArray(needle)); QByteArrayMatcher matcher2; matcher2.setPattern(QByteArray(needle)); @@ -90,8 +91,10 @@ void tst_QByteArrayMatcher::interface() QCOMPARE(matcher7.indexIn(haystack), 42); } - -static QByteArrayMatcher matcher; +#define LONG_STRING__32 "abcdefghijklmnopqrstuvwxyz012345" +#define LONG_STRING__64 LONG_STRING__32 LONG_STRING__32 +#define LONG_STRING_128 LONG_STRING__64 LONG_STRING__64 +#define LONG_STRING_256 LONG_STRING_128 LONG_STRING_128 void tst_QByteArrayMatcher::indexIn() { @@ -101,6 +104,8 @@ void tst_QByteArrayMatcher::indexIn() QByteArray haystack(8, '\0'); haystack[7] = 0x1; + QByteArrayMatcher matcher; + matcher = QByteArrayMatcher(pattern); QCOMPARE(matcher.indexIn(haystack, 0), 5); QCOMPARE(matcher.indexIn(haystack, 1), 5); @@ -110,7 +115,103 @@ void tst_QByteArrayMatcher::indexIn() QCOMPARE(matcher.indexIn(haystack, 0), 5); QCOMPARE(matcher.indexIn(haystack, 1), 5); QCOMPARE(matcher.indexIn(haystack, 2), 5); + + QByteArray allChars(256, Qt::Uninitialized); + for (int i = 0; i < 256; ++i) + allChars[i] = char(i); + + matcher = QByteArrayMatcher(allChars); + haystack = LONG_STRING__32 "x" + matcher.pattern(); + QCOMPARE(matcher.indexIn(haystack, 0), 33); + QCOMPARE(matcher.indexIn(haystack, 1), 33); + QCOMPARE(matcher.indexIn(haystack, 2), 33); + QCOMPARE(matcher.indexIn(haystack, 33), 33); + QCOMPARE(matcher.indexIn(haystack, 34), -1); + + matcher = QByteArrayMatcher(LONG_STRING_256); + haystack = LONG_STRING__32 "x" + matcher.pattern(); + QCOMPARE(matcher.indexIn(haystack, 0), 33); + QCOMPARE(matcher.indexIn(haystack, 1), 33); + QCOMPARE(matcher.indexIn(haystack, 2), 33); + QCOMPARE(matcher.indexIn(haystack, 33), 33); + QCOMPARE(matcher.indexIn(haystack, 34), -1); } +void tst_QByteArrayMatcher::staticByteArrayMatcher() +{ + { + static Q_RELAXED_CONSTEXPR auto smatcher = qMakeStaticByteArrayMatcher("Hello"); + QCOMPARE(smatcher.pattern(), QByteArrayLiteral("Hello")); + + QCOMPARE(smatcher.indexIn(QByteArray("Hello, World!")), 0); + QCOMPARE(smatcher.indexIn(QByteArray("Hello, World!"), 0), 0); + QCOMPARE(smatcher.indexIn(QByteArray("Hello, World!"), 1), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aHello, World!")), 1); + QCOMPARE(smatcher.indexIn(QByteArray("aaHello, World!")), 2); + QCOMPARE(smatcher.indexIn(QByteArray("aaaHello, World!")), 3); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaHello, World!")), 4); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaHello, World!")), 5); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaaHello, World!")), 6); + QCOMPARE(smatcher.indexIn(QByteArray("HHello, World!")), 1); + QCOMPARE(smatcher.indexIn(QByteArray("HeHello, World!")), 2); + QCOMPARE(smatcher.indexIn(QByteArray("HelHello, World!")), 3); + QCOMPARE(smatcher.indexIn(QByteArray("HellHello, World!")), 4); + QCOMPARE(smatcher.indexIn(QByteArray("HellaHello, World!")), 5); + QCOMPARE(smatcher.indexIn(QByteArray("HellauHello, World!")), 6); + QCOMPARE(smatcher.indexIn(QByteArray("aHella, World!")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaHella, World!")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaHella, World!")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaHella, World!")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaHella, World!")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaaHella, World!")), -1); + + QCOMPARE(smatcher.indexIn(QByteArray("aHello")), 1); + QCOMPARE(smatcher.indexIn(QByteArray("aaHello")), 2); + QCOMPARE(smatcher.indexIn(QByteArray("aaaHello")), 3); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaHello")), 4); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaHello")), 5); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaaHello")), 6); + QCOMPARE(smatcher.indexIn(QByteArray("HHello")), 1); + QCOMPARE(smatcher.indexIn(QByteArray("HeHello")), 2); + QCOMPARE(smatcher.indexIn(QByteArray("HelHello")), 3); + QCOMPARE(smatcher.indexIn(QByteArray("HellHello")), 4); + QCOMPARE(smatcher.indexIn(QByteArray("HellaHello")), 5); + QCOMPARE(smatcher.indexIn(QByteArray("HellauHello")), 6); + QCOMPARE(smatcher.indexIn(QByteArray("aHella")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaHella")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaHella")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaHella")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaHella")), -1); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaaHella")), -1); + } + + { + static Q_RELAXED_CONSTEXPR auto smatcher = qMakeStaticByteArrayMatcher(LONG_STRING_256); + QCOMPARE(smatcher.pattern(), QByteArrayLiteral(LONG_STRING_256)); + + QCOMPARE(smatcher.indexIn(QByteArray("a" LONG_STRING_256)), 1); + QCOMPARE(smatcher.indexIn(QByteArray("aa" LONG_STRING_256)), 2); + QCOMPARE(smatcher.indexIn(QByteArray("aaa" LONG_STRING_256)), 3); + QCOMPARE(smatcher.indexIn(QByteArray("aaaa" LONG_STRING_256)), 4); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaa" LONG_STRING_256)), 5); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaa" LONG_STRING_256)), 6); + QCOMPARE(smatcher.indexIn(QByteArray("a" LONG_STRING_256 "a")), 1); + QCOMPARE(smatcher.indexIn(QByteArray("aa" LONG_STRING_256 "a")), 2); + QCOMPARE(smatcher.indexIn(QByteArray("aaa" LONG_STRING_256 "a")), 3); + QCOMPARE(smatcher.indexIn(QByteArray("aaaa" LONG_STRING_256 "a")), 4); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaa" LONG_STRING_256 "a")), 5); + QCOMPARE(smatcher.indexIn(QByteArray("aaaaaa" LONG_STRING_256 "a")), 6); + QCOMPARE(smatcher.indexIn(QByteArray(LONG_STRING__32 "x" LONG_STRING_256)), 33); + QCOMPARE(smatcher.indexIn(QByteArray(LONG_STRING__64 "x" LONG_STRING_256)), 65); + QCOMPARE(smatcher.indexIn(QByteArray(LONG_STRING_128 "x" LONG_STRING_256)), 129); + } + +} + +#undef LONG_STRING_256 +#undef LONG_STRING_128 +#undef LONG_STRING__64 +#undef LONG_STRING__32 + QTEST_APPLESS_MAIN(tst_QByteArrayMatcher) #include "tst_qbytearraymatcher.moc" diff --git a/tests/auto/corelib/tools/qchar/tst_qchar.cpp b/tests/auto/corelib/tools/qchar/tst_qchar.cpp index fb436b67d6..13898ace7b 100644 --- a/tests/auto/corelib/tools/qchar/tst_qchar.cpp +++ b/tests/auto/corelib/tools/qchar/tst_qchar.cpp @@ -108,7 +108,7 @@ void tst_QChar::operators_data() for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) - QTest::newRow(qPrintable(QString::asprintf("'\\%d' (op) '\\%d'", i, j))) + QTest::addRow("'\\%d' (op) '\\%d'", i, j) << QChar(ushort(i)) << QChar(ushort(j)); } } diff --git a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp index 4604e664b0..5f9f5fbb6f 100644 --- a/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp +++ b/tests/auto/corelib/tools/qdatetime/tst_qdatetime.cpp @@ -77,8 +77,10 @@ private slots: void fromMSecsSinceEpoch(); void toString_isoDate_data(); void toString_isoDate(); + void toString_isoDate_extra(); void toString_textDate_data(); void toString_textDate(); + void toString_textDate_extra(); void toString_rfcDate_data(); void toString_rfcDate(); void toString_enumformat(); @@ -153,8 +155,6 @@ private: QDateTime invalidDateTime() const { return QDateTime(invalidDate(), invalidTime()); } QDate invalidDate() const { return QDate(); } QTime invalidTime() const { return QTime(-1, -1, -1); } - qint64 minJd() const { return QDateTimePrivate::minJd(); } - qint64 maxJd() const { return QDateTimePrivate::maxJd(); } }; Q_DECLARE_METATYPE(Qt::TimeSpec) @@ -606,10 +606,8 @@ void tst_QDateTime::setMSecsSinceEpoch_data() << QDateTime(QDate::fromJulianDay(0x7fffffff), QTime(21, 59, 59, 999), Qt::UTC) << QDateTime(QDate::fromJulianDay(0x7fffffff), QTime(23, 59, 59, 999)); QTest::newRow("min") - // + 1 because, in the reference check below, calling addMSecs(qint64min) - // will internally apply unary minus to -qint64min, resulting in a - // positive value 1 too big for qint64max, causing an overflow. - << std::numeric_limits<qint64>::min() + 1 + // Use -max(), which is min() + 1, to simplify filtering out overflow cases: + << -std::numeric_limits<qint64>::max() << QDateTime(QDate(-292275056, 5, 16), QTime(16, 47, 4, 193), Qt::UTC) << QDateTime(QDate(-292275056, 5, 16), QTime(17, 47, 4, 193), Qt::LocalTime); QTest::newRow("max") @@ -687,8 +685,8 @@ void tst_QDateTime::fromMSecsSinceEpoch() QDateTime dtUtc = QDateTime::fromMSecsSinceEpoch(msecs, Qt::UTC); QDateTime dtOffset = QDateTime::fromMSecsSinceEpoch(msecs, Qt::OffsetFromUTC, 60*60); - // LocalTime will overflow for min or max, depending on whether you're - // East or West of Greenwich. The test passes at GMT. + // LocalTime will overflow for "min" or "max" tests, depending on whether + // you're East or West of Greenwich. In UTC, we won't overflow. if (localTimeType == LocalTimeIsUtc || msecs != std::numeric_limits<qint64>::max() * localTimeType) QCOMPARE(dtLocal, utc); @@ -794,6 +792,28 @@ void tst_QDateTime::toString_isoDate() QLocale::setDefault(oldLocale); } +void tst_QDateTime::toString_isoDate_extra() +{ + QDateTime dt = QDateTime::fromMSecsSinceEpoch(0, Qt::UTC); + QCOMPARE(dt.toString(Qt::ISODate), QLatin1String("1970-01-01T00:00:00Z")); +#if QT_CONFIG(timezone) + QTimeZone PST("America/Vancouver"); + if (PST.isValid()) { + dt = QDateTime::fromMSecsSinceEpoch(0, PST); + QCOMPARE(dt.toString(Qt::ISODate), QLatin1String("1969-12-31T16:00:00-08:00")); + } else { + qDebug("Missed zone test: no America/Vancouver zone available"); + } + QTimeZone CET("Europe/Berlin"); + if (CET.isValid()) { + dt = QDateTime::fromMSecsSinceEpoch(0, CET); + QCOMPARE(dt.toString(Qt::ISODate), QLatin1String("1970-01-01T01:00:00+01:00")); + } else { + qDebug("Missed zone test: no Europe/Berlin zone available"); + } +#endif // timezone +} + void tst_QDateTime::toString_textDate_data() { QTest::addColumn<QDateTime>("datetime"); @@ -831,6 +851,49 @@ void tst_QDateTime::toString_textDate() QCOMPARE(resultDatetime.utcOffset(), datetime.utcOffset()); } +void tst_QDateTime::toString_textDate_extra() +{ + QLatin1String GMT("GMT"); + QDateTime dt = QDateTime::fromMSecsSinceEpoch(0, Qt::LocalTime); + QVERIFY(!dt.toString().endsWith(GMT)); + dt = QDateTime::fromMSecsSinceEpoch(0, Qt::UTC).toLocalTime(); + QVERIFY(!dt.toString().endsWith(GMT)); + if (QTimeZone::systemTimeZone().offsetFromUtc(dt)) + QVERIFY(dt.toString() != QLatin1String("Thu Jan 1 00:00:00 1970")); + else + QCOMPARE(dt.toString(), QLatin1String("Thu Jan 1 00:00:00 1970")); +#if QT_CONFIG(timezone) + QTimeZone PST("America/Vancouver"); + if (PST.isValid()) { + dt = QDateTime::fromMSecsSinceEpoch(0, PST); +# if defined Q_OS_UNIX && !defined Q_OS_DARWIN + QCOMPARE(dt.toString(), QLatin1String("Wed Dec 31 16:00:00 1969 PST")); +# else // QTBUG-57320, QTBUG-57298 + QVERIFY(dt.toString().startsWith(QLatin1String("Wed Dec 31 16:00:00 1969 "))); +# endif + dt = dt.toLocalTime(); + QVERIFY(!dt.toString().endsWith(GMT)); + } else { + qDebug("Missed zone test: no America/Vancouver zone available"); + } + QTimeZone CET("Europe/Berlin"); + if (CET.isValid()) { + dt = QDateTime::fromMSecsSinceEpoch(0, CET); +# if defined Q_OS_UNIX && !defined Q_OS_DARWIN + QCOMPARE(dt.toString(), QLatin1String("Thu Jan 1 01:00:00 1970 CET")); +# else // QTBUG-57320, QTBUG-57298 + QVERIFY(dt.toString().startsWith(QLatin1String("Thu Jan 1 01:00:00 1970 "))); +# endif + dt = dt.toLocalTime(); + QVERIFY(!dt.toString().endsWith(GMT)); + } else { + qDebug("Missed zone test: no Europe/Berlin zone available"); + } +#endif // timezone + dt = QDateTime::fromMSecsSinceEpoch(0, Qt::UTC); + QVERIFY(dt.toString().endsWith(GMT)); +} + void tst_QDateTime::toString_rfcDate_data() { QTest::addColumn<QDateTime>("dt"); @@ -3145,17 +3208,17 @@ void tst_QDateTime::timeZones() const // Test local to MSecs // - Test first occurrence 02:00:00 = 1 hour before tran hourBeforeStd = QDateTime(QDate(2013, 10, 27), QTime(2, 0, 0), cet); + QEXPECT_FAIL("", "QDateTime doesn't properly support Daylight Transitions", Continue); QCOMPARE(hourBeforeStd.toMSecsSinceEpoch(), dstToStdMSecs - 3600000); // - Test first occurrence 02:59:59.999 = 1 msec before tran msecBeforeStd = QDateTime(QDate(2013, 10, 27), QTime(2, 59, 59, 999), cet); + QEXPECT_FAIL("", "QDateTime doesn't properly support Daylight Transitions", Continue); QCOMPARE(msecBeforeStd.toMSecsSinceEpoch(), dstToStdMSecs - 1); // - Test second occurrence 02:00:00 = at tran atStd = QDateTime(QDate(2013, 10, 27), QTime(2, 0, 0), cet); - QEXPECT_FAIL("", "QDateTime doesn't properly support Daylight Transitions", Continue); QCOMPARE(atStd.toMSecsSinceEpoch(), dstToStdMSecs); // - Test second occurrence 03:00:00 = 59 mins after tran afterStd = QDateTime(QDate(2013, 10, 27), QTime(2, 59, 59, 999), cet); - QEXPECT_FAIL("", "QDateTime doesn't properly support Daylight Transitions", Continue); QCOMPARE(afterStd.toMSecsSinceEpoch(), dstToStdMSecs + 3600000 - 1); // - Test 03:00:00 = 1 hour after tran hourAfterStd = QDateTime(QDate(2013, 10, 27), QTime(3, 0, 0), cet); diff --git a/tests/auto/corelib/tools/qlatin1string/tst_qlatin1string.cpp b/tests/auto/corelib/tools/qlatin1string/tst_qlatin1string.cpp index 06e2e1cc45..a68671d899 100644 --- a/tests/auto/corelib/tools/qlatin1string/tst_qlatin1string.cpp +++ b/tests/auto/corelib/tools/qlatin1string/tst_qlatin1string.cpp @@ -176,9 +176,9 @@ void tst_QLatin1String::relationalOperators_data() for (Data *lhs = data; lhs != data + sizeof data / sizeof *data; ++lhs) { for (Data *rhs = data; rhs != data + sizeof data / sizeof *data; ++rhs) { QLatin1StringContainer l = { lhs->l1 }, r = { rhs->l1 }; - QTest::newRow(qPrintable(QString::asprintf("\"%s\" <> \"%s\"", - lhs->l1.data() ? lhs->l1.data() : "nullptr", - rhs->l1.data() ? rhs->l1.data() : "nullptr"))) + QTest::addRow("\"%s\" <> \"%s\"", + lhs->l1.data() ? lhs->l1.data() : "nullptr", + rhs->l1.data() ? rhs->l1.data() : "nullptr") << l << lhs->order << r << rhs->order; } } diff --git a/tests/auto/corelib/tools/qlocale/test/test.pro b/tests/auto/corelib/tools/qlocale/test/test.pro index 595ee258e7..c87e29e764 100644 --- a/tests/auto/corelib/tools/qlocale/test/test.pro +++ b/tests/auto/corelib/tools/qlocale/test/test.pro @@ -1,5 +1,4 @@ CONFIG += console testcase -CONFIG -= app_bundle QT = core testlib core-private embedded: QT += gui SOURCES = ../tst_qlocale.cpp diff --git a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp index 42bfb3603d..f56cff4d29 100644 --- a/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp +++ b/tests/auto/corelib/tools/qlocale/tst_qlocale.cpp @@ -1791,6 +1791,30 @@ void tst_QLocale::numberOptions() QVERIFY(ok); locale.toDouble(QString("1.24e+01"), &ok); QVERIFY(!ok); + + QCOMPARE(locale.toString(12.4, 'g', 5), QString("12.4")); + locale.setNumberOptions(QLocale::IncludeTrailingZeroesAfterDot); + QCOMPARE(locale.numberOptions(), QLocale::IncludeTrailingZeroesAfterDot); + QCOMPARE(locale.toString(12.4, 'g', 5), QString("12.400")); + + locale.toDouble(QString("1.24e+01"), &ok); + QVERIFY(ok); + locale.toDouble(QString("1.2400e+01"), &ok); + QVERIFY(ok); + locale.toDouble(QString("12.4"), &ok); + QVERIFY(ok); + locale.toDouble(QString("12.400"), &ok); + QVERIFY(ok); + locale.setNumberOptions(QLocale::RejectTrailingZeroesAfterDot); + QCOMPARE(locale.numberOptions(), QLocale::RejectTrailingZeroesAfterDot); + locale.toDouble(QString("1.24e+01"), &ok); + QVERIFY(ok); + locale.toDouble(QString("1.2400e+01"), &ok); + QVERIFY(!ok); + locale.toDouble(QString("12.4"), &ok); + QVERIFY(ok); + locale.toDouble(QString("12.400"), &ok); + QVERIFY(!ok); } void tst_QLocale::negativeNumbers() diff --git a/tests/auto/corelib/tools/qstring/tst_qstring.cpp b/tests/auto/corelib/tools/qstring/tst_qstring.cpp index 414ba2d8cf..6ed7b74277 100644 --- a/tests/auto/corelib/tools/qstring/tst_qstring.cpp +++ b/tests/auto/corelib/tools/qstring/tst_qstring.cpp @@ -6070,6 +6070,14 @@ void tst_QString::compare_data() lower += QChar(QChar::lowSurrogate(0x10428)); QTest::newRow("data8") << upper << lower << -1 << 0; + QTest::newRow("vectorized-boundaries-7") << QString("1234567") << QString("abcdefg") << -1 << -1; + QTest::newRow("vectorized-boundaries-8") << QString("12345678") << QString("abcdefgh") << -1 << -1; + QTest::newRow("vectorized-boundaries-9") << QString("123456789") << QString("abcdefghi") << -1 << -1; + + QTest::newRow("vectorized-boundaries-15") << QString("123456789012345") << QString("abcdefghiklmnop") << -1 << -1; + QTest::newRow("vectorized-boundaries-16") << QString("1234567890123456") << QString("abcdefghiklmnopq") << -1 << -1; + QTest::newRow("vectorized-boundaries-17") << QString("12345678901234567") << QString("abcdefghiklmnopqr") << -1 << -1; + // embedded nulls // These don't work as of now. It's OK that these don't work since \0 is not a valid unicode /*QTest::newRow("data10") << QString(QByteArray("\0", 1)) << QString(QByteArray("\0", 1)) << 0 << 0; diff --git a/tests/auto/corelib/tools/qtimezone/qtimezone.pro b/tests/auto/corelib/tools/qtimezone/qtimezone.pro index afc4c59dfe..19ebc13306 100644 --- a/tests/auto/corelib/tools/qtimezone/qtimezone.pro +++ b/tests/auto/corelib/tools/qtimezone/qtimezone.pro @@ -5,3 +5,8 @@ SOURCES = tst_qtimezone.cpp qtConfig(icu) { DEFINES += QT_USE_ICU } + +darwin { + OBJECTIVE_SOURCES += tst_qtimezone_darwin.mm + LIBS += -framework Foundation +} diff --git a/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp b/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp index c631b395f8..abb5b50229 100644 --- a/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp +++ b/tests/auto/corelib/tools/qtimezone/tst_qtimezone.cpp @@ -45,6 +45,8 @@ private slots: void dataStreamTest(); void isTimeZoneIdAvailable(); void availableTimeZoneIds(); + void transitionEachZone_data(); + void transitionEachZone(); void stressTest(); void windowsId(); void isValidId_data(); @@ -54,23 +56,24 @@ private slots: void icuTest(); void tzTest(); void macTest(); + void darwinTypes(); void winTest(); private: - void printTimeZone(const QTimeZone tz); + void printTimeZone(const QTimeZone &tz); #ifdef QT_BUILD_INTERNAL void testCetPrivate(const QTimeZonePrivate &tzp); #endif // QT_BUILD_INTERNAL - bool debug; + const bool debug; }; tst_QTimeZone::tst_QTimeZone() -{ // Set to true to print debug output, test Display Names and run long stress tests - debug = false; + : debug(false) +{ } -void tst_QTimeZone::printTimeZone(const QTimeZone tz) +void tst_QTimeZone::printTimeZone(const QTimeZone &tz) { QDateTime now = QDateTime::currentDateTime(); QDateTime jan = QDateTime(QDate(2012, 1, 1), QTime(0, 0, 0), Qt::UTC); @@ -367,6 +370,56 @@ void tst_QTimeZone::isTimeZoneIdAvailable() QCOMPARE(QTimeZonePrivate::isValidId("12345678901234/123456789012345"), false); } +void tst_QTimeZone::transitionEachZone_data() +{ + QTest::addColumn<QByteArray>("zone"); + QTest::addColumn<qint64>("secs"); + QTest::addColumn<int>("start"); + QTest::addColumn<int>("stop"); + + struct { + qint64 baseSecs; + int start, stop; + int year; + } table[] = { + { 25666200, 3, 12, 1970 }, // 1970-10-25 01:30 UTC; North America + { 1288488600, -4, 8, 2010 } // 2010-10-31 01:30 UTC; Europe, Russia + }; + + QString name; + for (int k = sizeof(table) / sizeof(table[0]); k-- > 0; ) { + foreach (QByteArray zone, QTimeZone::availableTimeZoneIds()) { + name.sprintf("%s@%d", zone.constData(), table[k].year); + QTest::newRow(name.toUtf8().constData()) + << zone + << table[k].baseSecs + << table[k].start + << table[k].stop; + } + } +} + +void tst_QTimeZone::transitionEachZone() +{ + // Regression test: round-trip fromMsecs/toMSecs should be idempotent; but + // various zones failed during fall-back transitions. + QFETCH(QByteArray, zone); + QFETCH(qint64, secs); + QFETCH(int, start); + QFETCH(int, stop); + QTimeZone named(zone); + + for (int i = start; i < stop; i++) { + qint64 here = secs + i * 3600; + QDateTime when = QDateTime::fromMSecsSinceEpoch(here * 1000, named); + qint64 stamp = when.toMSecsSinceEpoch(); + if (here * 1000 != stamp) // (The +1 is due to using *1*:30 as baseSecs.) + qDebug() << "Failing for" << zone << "at half past" << (i + 1) << "UTC"; + QCOMPARE(stamp % 1000, 0); + QCOMPARE(here - stamp / 1000, 0); + } +} + void tst_QTimeZone::availableTimeZoneIds() { if (debug) { @@ -704,9 +757,9 @@ void tst_QTimeZone::tzTest() // Test display names by type, either ICU or abbreviation only QLocale enUS("en_US"); -#ifdef QT_USE_ICU // Only test names in debug mode, names used can vary by ICU version installed if (debug) { +#ifdef QT_USE_ICU QCOMPARE(tzp.displayName(QTimeZone::StandardTime, QTimeZone::LongName, enUS), QString("Central European Standard Time")); QCOMPARE(tzp.displayName(QTimeZone::StandardTime, QTimeZone::ShortName, enUS), @@ -726,9 +779,7 @@ void tst_QTimeZone::tzTest() QString("GMT+01:00")); QCOMPARE(tzp.displayName(QTimeZone::GenericTime, QTimeZone::OffsetName, enUS), QString("UTC+01:00")); - } #else - if (debug) { QCOMPARE(tzp.displayName(QTimeZone::StandardTime, QTimeZone::LongName, enUS), QString("CET")); QCOMPARE(tzp.displayName(QTimeZone::StandardTime, QTimeZone::ShortName, enUS), @@ -747,10 +798,8 @@ void tst_QTimeZone::tzTest() QString("CET")); QCOMPARE(tzp.displayName(QTimeZone::GenericTime, QTimeZone::OffsetName, enUS), QString("CET")); - } #endif // QT_USE_ICU - if (debug) { // Test Abbreviations QCOMPARE(tzp.abbreviation(std), QString("CET")); QCOMPARE(tzp.abbreviation(dst), QString("CEST")); @@ -907,6 +956,16 @@ void tst_QTimeZone::macTest() #endif // Q_OS_MAC } +void tst_QTimeZone::darwinTypes() +{ +#ifndef Q_OS_DARWIN + QSKIP("This is an Apple-only test"); +#else + extern void tst_QTimeZone_darwinTypes(); // in tst_qtimezone_darwin.mm + tst_QTimeZone_darwinTypes(); +#endif +} + void tst_QTimeZone::winTest() { #if defined(QT_BUILD_INTERNAL) && defined(Q_OS_WIN) diff --git a/tests/auto/corelib/tools/qtimezone/tst_qtimezone_darwin.mm b/tests/auto/corelib/tools/qtimezone/tst_qtimezone_darwin.mm new file mode 100644 index 0000000000..de801e55d0 --- /dev/null +++ b/tests/auto/corelib/tools/qtimezone/tst_qtimezone_darwin.mm @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2017 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/QTimeZone> +#include <QtTest/QtTest> + +#include <CoreFoundation/CoreFoundation.h> +#include <Foundation/Foundation.h> + +void tst_QTimeZone_darwinTypes() +{ +#if !defined(QT_NO_SYSTEMLOCALE) + // QTimeZone <-> CFTimeZone + { + QTimeZone qtTimeZone("America/Los_Angeles"); + const CFTimeZoneRef cfTimeZone = qtTimeZone.toCFTimeZone(); + QCOMPARE(QTimeZone::fromCFTimeZone(cfTimeZone), qtTimeZone); + CFRelease(cfTimeZone); + } + { + CFTimeZoneRef cfTimeZone = CFTimeZoneCreateWithName(kCFAllocatorDefault, + CFSTR("America/Los_Angeles"), false); + const QTimeZone qtTimeZone = QTimeZone::fromCFTimeZone(cfTimeZone); + QVERIFY(CFEqual(qtTimeZone.toCFTimeZone(), cfTimeZone)); + CFRelease(cfTimeZone); + } + // QTimeZone <-> NSTimeZone + { + NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; + QTimeZone qtTimeZone("America/Los_Angeles"); + const NSTimeZone *nsTimeZone = qtTimeZone.toNSTimeZone(); + QCOMPARE(QTimeZone::fromNSTimeZone(nsTimeZone), qtTimeZone); + [autoreleasepool release]; + } + { + NSAutoreleasePool *autoreleasepool = [[NSAutoreleasePool alloc] init]; + NSTimeZone *nsTimeZone = [NSTimeZone timeZoneWithName:@"America/Los_Angeles"]; + const QTimeZone qtTimeZone = QTimeZone::fromNSTimeZone(nsTimeZone); + QVERIFY([qtTimeZone.toNSTimeZone() isEqual:nsTimeZone]); + [autoreleasepool release]; + } +#endif +} diff --git a/tests/auto/gui/image/qimage/tst_qimage.cpp b/tests/auto/gui/image/qimage/tst_qimage.cpp index 2433fa4115..21481e374d 100644 --- a/tests/auto/gui/image/qimage/tst_qimage.cpp +++ b/tests/auto/gui/image/qimage/tst_qimage.cpp @@ -206,6 +206,11 @@ private slots: void ditherGradient_data(); void ditherGradient(); + void reinterpretAsFormat_data(); + void reinterpretAsFormat(); + + void reinterpretAsFormat2(); + #ifdef Q_OS_DARWIN void toCGImage_data(); void toCGImage(); @@ -1088,35 +1093,11 @@ void tst_QImage::rotate_data() degrees << 0 << 90 << 180 << 270; foreach (int d, degrees) { - const QByteArray dB = QByteArray::number(d); - QTest::newRow((dB + " Format_RGB32").constData()) - << QImage::Format_RGB32 << d; - QTest::newRow((dB + " Format_ARGB32").constData()) - << QImage::Format_ARGB32 << d; - QTest::newRow((dB + " Format_ARGB32_Premultiplied").constData()) - << QImage::Format_ARGB32_Premultiplied << d; - QTest::newRow((dB + " Format_RGB16").constData()) - << QImage::Format_RGB16 << d; - QTest::newRow((dB + " Format_ARGB8565_Premultiplied").constData()) - << QImage::Format_ARGB8565_Premultiplied << d; - QTest::newRow((dB + " Format_RGB666").constData()) - << QImage::Format_RGB666 << d; - QTest::newRow((dB + " Format_RGB555").constData()) - << QImage::Format_RGB555 << d; - QTest::newRow((dB + " Format_ARGB8555_Premultiplied").constData()) - << QImage::Format_ARGB8555_Premultiplied << d; - QTest::newRow((dB + " Format_RGB888").constData()) - << QImage::Format_RGB888 << d; - QTest::newRow((dB + " Format_Indexed8").constData()) - << QImage::Format_Indexed8 << d; - QTest::newRow((dB + " Format_RGBX8888").constData()) - << QImage::Format_RGBX8888 << d; - QTest::newRow((dB + " Format_RGBA8888_Premultiplied").constData()) - << QImage::Format_RGBA8888_Premultiplied << d; - QTest::newRow((dB + " Format_Alpha8").constData()) - << QImage::Format_Alpha8 << d; - QTest::newRow((dB + " Format_Grayscale8").constData()) - << QImage::Format_Grayscale8 << d; + const QString dB = QString::number(d); + for (int i = QImage::Format_Indexed8; i < QImage::NImageFormats; i++) { + QImage::Format format = static_cast<QImage::Format>(i); + QTest::newRow(qPrintable(dB + " " + formatToString(format))) << format << d; + } } } @@ -3327,6 +3308,64 @@ void tst_QImage::ditherGradient() QVERIFY(observedGradientSteps >= minimumExpectedGradient); } +void tst_QImage::reinterpretAsFormat_data() +{ + QTest::addColumn<QImage::Format>("in_format"); + QTest::addColumn<QImage::Format>("out_format"); + QTest::addColumn<QColor>("in_color"); + QTest::addColumn<QColor>("out_color"); + +#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN + QTest::newRow("rgb32 -> rgbx8888") << QImage::Format_RGB32 << QImage::Format_RGBX8888 << QColor(Qt::red) << QColor(Qt::blue); + QTest::newRow("rgba8888 -> argb32") << QImage::Format_RGBA8888 << QImage::Format_ARGB32 << QColor(Qt::red) << QColor(Qt::blue); + QTest::newRow("argb32pm -> rgba8888pm") << QImage::Format_RGBA8888_Premultiplied << QImage::Format_ARGB32_Premultiplied << QColor(Qt::green) << QColor(Qt::green); +#endif + QTest::newRow("rgb32 -> argb32") << QImage::Format_RGB32 << QImage::Format_ARGB32 << QColor(Qt::cyan) << QColor(Qt::cyan); + QTest::newRow("argb32pm -> rgb32") << QImage::Format_ARGB32_Premultiplied << QImage::Format_RGB32 << QColor(Qt::transparent) << QColor(Qt::black); + QTest::newRow("argb32 -> rgb32") << QImage::Format_ARGB32 << QImage::Format_RGB32 << QColor(255, 0, 0, 127) << QColor(255, 0, 0); + QTest::newRow("argb32pm -> rgb32") << QImage::Format_ARGB32_Premultiplied << QImage::Format_RGB32 << QColor(255, 0, 0, 127) << QColor(127, 0, 0); +} + +void tst_QImage::reinterpretAsFormat() +{ + QFETCH(QImage::Format, in_format); + QFETCH(QImage::Format, out_format); + QFETCH(QColor, in_color); + QFETCH(QColor, out_color); + + QImage image(1, 1, in_format); + image.setPixelColor(0, 0, in_color); + QVERIFY(image.reinterpretAsFormat(out_format)); + QCOMPARE(image.pixelColor(0, 0), out_color); +} + +void tst_QImage::reinterpretAsFormat2() +{ + const uint imageData[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + + { + QImage image(reinterpret_cast<const uchar*>(imageData), 4, 2, QImage::Format_RGB32); + QCOMPARE(image.pixelColor(0, 0), QColor(Qt::black)); + QVERIFY(image.isDetached()); + QVERIFY(image.reinterpretAsFormat(QImage::Format_ARGB32_Premultiplied)); + QCOMPARE(image.constBits(), reinterpret_cast<const uchar*>(imageData)); + QCOMPARE(image.pixelColor(0, 0), QColor(Qt::transparent)); + + QVERIFY(!image.reinterpretAsFormat(QImage::Format_Grayscale8)); + } + { + QImage image(reinterpret_cast<const uchar*>(imageData), 8, 4, QImage::Format_Indexed8); + image.setColor(0, qRgb(255, 255, 255)); + QCOMPARE(image.pixelColor(0, 0), QColor(Qt::white)); + QVERIFY(image.reinterpretAsFormat(QImage::Format_Grayscale8)); + QCOMPARE(image.pixelColor(0, 0), QColor(Qt::black)); + QVERIFY(image.reinterpretAsFormat(QImage::Format_Alpha8)); + QCOMPARE(image.pixelColor(0, 0), QColor(Qt::transparent)); + + QVERIFY(!image.reinterpretAsFormat(QImage::Format_RGB16)); + } +} + #ifdef Q_OS_DARWIN void tst_QImage::toCGImage_data() diff --git a/tests/auto/gui/image/qimagewriter/tst_qimagewriter.cpp b/tests/auto/gui/image/qimagewriter/tst_qimagewriter.cpp index 191aabdf6a..d5c624833c 100644 --- a/tests/auto/gui/image/qimagewriter/tst_qimagewriter.cpp +++ b/tests/auto/gui/image/qimagewriter/tst_qimagewriter.cpp @@ -47,7 +47,7 @@ #include <algorithm> typedef QMap<QString, QString> QStringMap; -typedef QList<int> QIntList; +typedef QVector<int> QIntList; Q_DECLARE_METATYPE(QImageWriter::ImageWriterError) Q_DECLARE_METATYPE(QImage::Format) @@ -227,8 +227,15 @@ void tst_QImageWriter::writeImage2_data() QTest::addColumn<QByteArray>("format"); QTest::addColumn<QImage>("image"); - const QStringList formats = QStringList() << "bmp" << "xpm" << "png" - << "ppm" << "ico"; //<< "jpeg"; + static const QLatin1String formats[] = { + QLatin1String("bmp"), + QLatin1String("xpm"), + QLatin1String("png"), + QLatin1String("ppm"), + QLatin1String("ico"), + // QLatin1String("jpeg"), + }; + QImage image0(70, 70, QImage::Format_ARGB32); image0.fill(QColor(Qt::red).rgb()); @@ -236,11 +243,11 @@ void tst_QImageWriter::writeImage2_data() while (imgFormat != QImage::NImageFormats) { QImage image = image0.convertToFormat(imgFormat); initializePadding(&image); - foreach (const QString format, formats) { + for (QLatin1String format : formats) { const QString fileName = QLatin1String("solidcolor_") + QString::number(imgFormat) + QLatin1Char('.') + format; QTest::newRow(fileName.toLatin1()) << writePrefix + fileName - << format.toLatin1() + << QByteArray(format.data(), format.size()) << image; } imgFormat = QImage::Format(int(imgFormat) + 1); @@ -304,41 +311,38 @@ void tst_QImageWriter::writeImage2() QVERIFY(QFile::remove(fileName)); } +namespace { +// C++98-library version of C++11 std::is_sorted +template <typename C> +bool is_sorted(const C &c) +{ + return std::adjacent_find(c.begin(), c.end(), std::greater_equal<typename C::value_type>()) == c.end(); +} +} + void tst_QImageWriter::supportedFormats() { QList<QByteArray> formats = QImageWriter::supportedImageFormats(); - QList<QByteArray> sortedFormats = formats; - std::sort(sortedFormats.begin(), sortedFormats.end()); // check that the list is sorted - QCOMPARE(formats, sortedFormats); - - QSet<QByteArray> formatSet; - foreach (QByteArray format, formats) - formatSet << format; + QVERIFY(is_sorted(formats)); // check that the list does not contain duplicates - QCOMPARE(formatSet.size(), formats.size()); + QVERIFY(std::unique(formats.begin(), formats.end()) == formats.end()); } void tst_QImageWriter::supportedMimeTypes() { QList<QByteArray> mimeTypes = QImageWriter::supportedMimeTypes(); - QList<QByteArray> sortedMimeTypes = mimeTypes; - std::sort(sortedMimeTypes.begin(), sortedMimeTypes.end()); // check that the list is sorted - QCOMPARE(mimeTypes, sortedMimeTypes); - - QSet<QByteArray> mimeTypeSet; - foreach (QByteArray mimeType, mimeTypes) - mimeTypeSet << mimeType; + QVERIFY(is_sorted(mimeTypes)); // check the list as a minimum contains image/bmp - QVERIFY(mimeTypeSet.contains("image/bmp")); + QVERIFY(mimeTypes.contains("image/bmp")); // check that the list does not contain duplicates - QCOMPARE(mimeTypeSet.size(), mimeTypes.size()); + QVERIFY(std::unique(mimeTypes.begin(), mimeTypes.end()) == mimeTypes.end()); } void tst_QImageWriter::writeToInvalidDevice() @@ -412,30 +416,27 @@ void tst_QImageWriter::supportsOption() QFETCH(QString, fileName); QFETCH(QIntList, options); - QSet<QImageIOHandler::ImageOption> allOptions; - allOptions << QImageIOHandler::Size - << QImageIOHandler::ClipRect - << QImageIOHandler::Description - << QImageIOHandler::ScaledClipRect - << QImageIOHandler::ScaledSize - << QImageIOHandler::CompressionRatio - << QImageIOHandler::Gamma - << QImageIOHandler::Quality - << QImageIOHandler::Name - << QImageIOHandler::SubType - << QImageIOHandler::IncrementalReading - << QImageIOHandler::Endianness - << QImageIOHandler::Animation - << QImageIOHandler::BackgroundColor; + static Q_CONSTEXPR QImageIOHandler::ImageOption allOptions[] = { + QImageIOHandler::Size, + QImageIOHandler::ClipRect, + QImageIOHandler::Description, + QImageIOHandler::ScaledClipRect, + QImageIOHandler::ScaledSize, + QImageIOHandler::CompressionRatio, + QImageIOHandler::Gamma, + QImageIOHandler::Quality, + QImageIOHandler::Name, + QImageIOHandler::SubType, + QImageIOHandler::IncrementalReading, + QImageIOHandler::Endianness, + QImageIOHandler::Animation, + QImageIOHandler::BackgroundColor, + }; QImageWriter writer(writePrefix + fileName); - for (int i = 0; i < options.size(); ++i) { - QVERIFY(writer.supportsOption(QImageIOHandler::ImageOption(options.at(i)))); - allOptions.remove(QImageIOHandler::ImageOption(options.at(i))); + for (auto option : allOptions) { + QCOMPARE(writer.supportsOption(option), options.contains(option)); } - - foreach (QImageIOHandler::ImageOption option, allOptions) - QVERIFY(!writer.supportsOption(option)); } void tst_QImageWriter::saveWithNoFormat_data() diff --git a/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp b/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp index ad7de09c48..72609d4095 100644 --- a/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp +++ b/tests/auto/gui/image/qpixmap/tst_qpixmap.cpp @@ -99,6 +99,7 @@ private slots: void task_51271(); void convertFromImageNoDetach(); + void convertFromImageNoDetach2(); void convertFromImageDetach(); void convertFromImageCacheKey(); @@ -766,6 +767,33 @@ void tst_QPixmap::convertFromImageNoDetach() QCOMPARE(constOrig.bits(), constCopy.bits()); } +void tst_QPixmap::convertFromImageNoDetach2() +{ + QPixmap randomPixmap(10, 10); + if (randomPixmap.handle()->classId() != QPlatformPixmap::RasterClass) + QSKIP("Test only valid for raster pixmaps"); + + //first get the screen format + QImage::Format screenFormat = randomPixmap.toImage().format(); + QVERIFY(screenFormat != QImage::Format_Invalid); + if (screenFormat != QImage::Format_RGB32 && + screenFormat != QImage::Format_ARGB32_Premultiplied) + QSKIP("Test only valid for platforms with RGB32 pixmaps"); + + QImage orig(100,100, QImage::Format_ARGB32_Premultiplied); + orig.fill(Qt::white); + + const uchar *origBits = orig.constBits(); + + QPixmap pix = QPixmap::fromImage(std::move(orig)); + QImage copy = pix.toImage(); + + QVERIFY(!copy.hasAlphaChannel()); + QCOMPARE(copy.format(), QImage::Format_RGB32); + + QCOMPARE(origBits, copy.constBits()); +} + void tst_QPixmap::convertFromImageDetach() { QImage img(10,10, QImage::Format_RGB32); diff --git a/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp b/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp index 364b9332af..ec143896ab 100644 --- a/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp +++ b/tests/auto/gui/kernel/qtouchevent/tst_qtouchevent.cpp @@ -36,6 +36,7 @@ #include <qpa/qwindowsysteminterface.h> #include <qpa/qwindowsysteminterface_p.h> #include <private/qhighdpiscaling_p.h> +#include <private/qtouchdevice_p.h> class tst_QTouchEventWidget : public QWidget { @@ -200,6 +201,7 @@ private slots: void touchBeginPropagatesWhenIgnored(); void touchUpdateAndEndNeverPropagate(); void basicRawEventTranslation(); + void basicRawEventTranslationOfIds(); void multiPointRawEventTranslationOnTouchScreen(); void multiPointRawEventTranslationOnTouchPad(); void deleteInEventHandler(); @@ -641,7 +643,8 @@ void tst_QTouchEvent::basicRawEventTranslation() QCOMPARE(touchWidget.touchBeginPoints.count(), 1); QCOMPARE(touchWidget.timestamp, timestamp); QTouchEvent::TouchPoint touchBeginPoint = touchWidget.touchBeginPoints.first(); - QCOMPARE(touchBeginPoint.id(), rawTouchPoint.id()); + const int touchPointId = (QTouchDevicePrivate::get(touchScreenDevice)->id << 24) + 1; + QCOMPARE(touchBeginPoint.id(), touchPointId); QCOMPARE(touchBeginPoint.state(), rawTouchPoint.state()); QCOMPARE(touchBeginPoint.pos(), pos); QCOMPARE(touchBeginPoint.startPos(), pos); @@ -676,7 +679,7 @@ void tst_QTouchEvent::basicRawEventTranslation() QVERIFY(!touchWidget.seenTouchEnd); QCOMPARE(touchWidget.touchUpdatePoints.count(), 1); QTouchEvent::TouchPoint touchUpdatePoint = touchWidget.touchUpdatePoints.first(); - QCOMPARE(touchUpdatePoint.id(), rawTouchPoint.id()); + QCOMPARE(touchUpdatePoint.id(), touchPointId); QCOMPARE(touchUpdatePoint.state(), rawTouchPoint.state()); QCOMPARE(touchUpdatePoint.pos(), pos + delta); QCOMPARE(touchUpdatePoint.startPos(), pos); @@ -708,7 +711,7 @@ void tst_QTouchEvent::basicRawEventTranslation() QVERIFY(touchWidget.seenTouchEnd); QCOMPARE(touchWidget.touchEndPoints.count(), 1); QTouchEvent::TouchPoint touchEndPoint = touchWidget.touchEndPoints.first(); - QCOMPARE(touchEndPoint.id(), rawTouchPoint.id()); + QCOMPARE(touchEndPoint.id(), touchPointId); QCOMPARE(touchEndPoint.state(), rawTouchPoint.state()); QCOMPARE(touchEndPoint.pos(), pos + delta + delta); QCOMPARE(touchEndPoint.startPos(), pos); @@ -784,9 +787,11 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QVERIFY(!rightWidget.seenTouchEnd); QCOMPARE(leftWidget.touchBeginPoints.count(), 1); QCOMPARE(rightWidget.touchBeginPoints.count(), 1); + const int touchPointId0 = (QTouchDevicePrivate::get(touchScreenDevice)->id << 24) + 1; + const int touchPointId1 = touchPointId0 + 1; { QTouchEvent::TouchPoint leftTouchPoint = leftWidget.touchBeginPoints.first(); - QCOMPARE(leftTouchPoint.id(), rawTouchPoints[0].id()); + QCOMPARE(leftTouchPoint.id(), touchPointId0); QCOMPARE(leftTouchPoint.state(), rawTouchPoints[0].state()); QCOMPARE(leftTouchPoint.pos(), leftPos); QCOMPARE(leftTouchPoint.startPos(), leftPos); @@ -806,7 +811,7 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QCOMPARE(leftTouchPoint.pressure(), qreal(1.)); QTouchEvent::TouchPoint rightTouchPoint = rightWidget.touchBeginPoints.first(); - QCOMPARE(rightTouchPoint.id(), rawTouchPoints[1].id()); + QCOMPARE(rightTouchPoint.id(), touchPointId1); QCOMPARE(rightTouchPoint.state(), rawTouchPoints[1].state()); QCOMPARE(rightTouchPoint.pos(), rightPos); QCOMPARE(rightTouchPoint.startPos(), rightPos); @@ -850,7 +855,7 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QCOMPARE(rightWidget.touchUpdatePoints.count(), 1); { QTouchEvent::TouchPoint leftTouchPoint = leftWidget.touchUpdatePoints.first(); - QCOMPARE(leftTouchPoint.id(), rawTouchPoints[0].id()); + QCOMPARE(leftTouchPoint.id(), touchPointId0); QCOMPARE(leftTouchPoint.state(), rawTouchPoints[0].state()); QCOMPARE(leftTouchPoint.pos(), QPointF(leftWidget.mapFromParent(centerPos.toPoint()))); QCOMPARE(leftTouchPoint.startPos(), leftPos); @@ -870,7 +875,7 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QCOMPARE(leftTouchPoint.pressure(), qreal(1.)); QTouchEvent::TouchPoint rightTouchPoint = rightWidget.touchUpdatePoints.first(); - QCOMPARE(rightTouchPoint.id(), rawTouchPoints[1].id()); + QCOMPARE(rightTouchPoint.id(), touchPointId1); QCOMPARE(rightTouchPoint.state(), rawTouchPoints[1].state()); QCOMPARE(rightTouchPoint.pos(), QPointF(rightWidget.mapFromParent(centerPos.toPoint()))); QCOMPARE(rightTouchPoint.startPos(), rightPos); @@ -914,7 +919,7 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QCOMPARE(rightWidget.touchEndPoints.count(), 1); { QTouchEvent::TouchPoint leftTouchPoint = leftWidget.touchEndPoints.first(); - QCOMPARE(leftTouchPoint.id(), rawTouchPoints[0].id()); + QCOMPARE(leftTouchPoint.id(), touchPointId0); QCOMPARE(leftTouchPoint.state(), rawTouchPoints[0].state()); QCOMPARE(leftTouchPoint.pos(), QPointF(leftWidget.mapFromParent(centerPos.toPoint()))); QCOMPARE(leftTouchPoint.startPos(), leftPos); @@ -934,7 +939,7 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchScreen() QCOMPARE(leftTouchPoint.pressure(), qreal(0.)); QTouchEvent::TouchPoint rightTouchPoint = rightWidget.touchEndPoints.first(); - QCOMPARE(rightTouchPoint.id(), rawTouchPoints[1].id()); + QCOMPARE(rightTouchPoint.id(), touchPointId1); QCOMPARE(rightTouchPoint.state(), rawTouchPoints[1].state()); QCOMPARE(rightTouchPoint.pos(), QPointF(rightWidget.mapFromParent(centerPos.toPoint()))); QCOMPARE(rightTouchPoint.startPos(), rightPos); @@ -1184,6 +1189,126 @@ void tst_QTouchEvent::multiPointRawEventTranslationOnTouchPad() } } +void tst_QTouchEvent::basicRawEventTranslationOfIds() +{ + if (!QGuiApplication::platformName().compare(QLatin1String("wayland"), Qt::CaseInsensitive)) + QSKIP("Wayland: This fails. Figure out why."); + + tst_QTouchEventWidget touchWidget; + touchWidget.setWindowTitle(QTest::currentTestFunction()); + touchWidget.setAttribute(Qt::WA_AcceptTouchEvents); + touchWidget.setGeometry(100, 100, 400, 300); + touchWidget.show(); + QVERIFY(QTest::qWaitForWindowActive(&touchWidget)); + + QVarLengthArray<QPointF, 2> pos; + QVarLengthArray<QPointF, 2> screenPos; + for (int i = 0; i < 2; ++i) { + pos << touchWidget.rect().center() + QPointF(20*i, 20*i); + screenPos << touchWidget.mapToGlobal(pos[i].toPoint()); + } + QPointF delta(10, 10); + QRectF screenGeometry = QApplication::desktop()->screenGeometry(&touchWidget); + + QVector<QPointF> rawPosList; + rawPosList << QPointF(12, 34) << QPointF(56, 78); + + QList<QTouchEvent::TouchPoint> rawTouchPoints; + + // Press both points, this should be translated to a TouchBegin + for (int i = 0; i < 2; ++i) { + QTouchEvent::TouchPoint rawTouchPoint; + rawTouchPoint.setId(i); + rawTouchPoint.setState(Qt::TouchPointPressed); + rawTouchPoint.setScreenPos(screenPos[i]); + rawTouchPoint.setNormalizedPos(normalized(rawTouchPoint.pos(), screenGeometry)); + rawTouchPoint.setRawScreenPositions(rawPosList); + rawTouchPoints << rawTouchPoint; + } + QTouchEvent::TouchPoint &p0 = rawTouchPoints[0]; + QTouchEvent::TouchPoint &p1 = rawTouchPoints[1]; + + const ulong timestamp = 1234; + QWindow *window = touchWidget.windowHandle(); + QList<QWindowSystemInterface::TouchPoint> nativeTouchPoints = + QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window); + QWindowSystemInterface::handleTouchEvent(window, timestamp, touchScreenDevice, nativeTouchPoints); + QCoreApplication::processEvents(); + QVERIFY(touchWidget.seenTouchBegin); + QVERIFY(!touchWidget.seenTouchUpdate); + QVERIFY(!touchWidget.seenTouchEnd); + QCOMPARE(touchWidget.touchBeginPoints.count(), 2); + + const int initialTouchPointId = (QTouchDevicePrivate::get(touchScreenDevice)->id << 24) + 1; + + for (int i = 0; i < touchWidget.touchBeginPoints.count(); ++i) { + QTouchEvent::TouchPoint touchBeginPoint = touchWidget.touchBeginPoints.at(i); + QCOMPARE(touchBeginPoint.id(), initialTouchPointId + i); + QCOMPARE(touchBeginPoint.state(), rawTouchPoints[i].state()); + } + + // moving the point should translate to TouchUpdate + for (int i = 0; i < rawTouchPoints.count(); ++i) { + QTouchEvent::TouchPoint &p = rawTouchPoints[i]; + p.setState(Qt::TouchPointMoved); + p.setScreenPos(p.screenPos() + delta); + p.setNormalizedPos(normalized(p.pos(), screenGeometry)); + } + nativeTouchPoints = + QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window); + QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints); + QCoreApplication::processEvents(); + QVERIFY(touchWidget.seenTouchBegin); + QVERIFY(touchWidget.seenTouchUpdate); + QVERIFY(!touchWidget.seenTouchEnd); + QCOMPARE(touchWidget.touchUpdatePoints.count(), 2); + QCOMPARE(touchWidget.touchUpdatePoints.at(0).id(), initialTouchPointId); + QCOMPARE(touchWidget.touchUpdatePoints.at(1).id(), initialTouchPointId + 1); + + // release last point + p0.setState(Qt::TouchPointStationary); + p1.setState(Qt::TouchPointReleased); + + nativeTouchPoints = + QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window); + QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints); + QCoreApplication::processEvents(); + QVERIFY(touchWidget.seenTouchBegin); + QVERIFY(touchWidget.seenTouchUpdate); + QVERIFY(!touchWidget.seenTouchEnd); + QCOMPARE(touchWidget.touchUpdatePoints.count(), 2); + QCOMPARE(touchWidget.touchUpdatePoints[0].id(), initialTouchPointId); + QCOMPARE(touchWidget.touchUpdatePoints[1].id(), initialTouchPointId + 1); + + // Press last point again, id should increase + p1.setState(Qt::TouchPointPressed); + p1.setId(42); // new id + nativeTouchPoints = + QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window); + QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints); + QCoreApplication::processEvents(); + QVERIFY(touchWidget.seenTouchBegin); + QVERIFY(touchWidget.seenTouchUpdate); + QVERIFY(!touchWidget.seenTouchEnd); + QCOMPARE(touchWidget.touchUpdatePoints.count(), 2); + QCOMPARE(touchWidget.touchUpdatePoints[0].id(), initialTouchPointId); + QCOMPARE(touchWidget.touchUpdatePoints[1].id(), initialTouchPointId + 2); + + // release everything + p0.setState(Qt::TouchPointReleased); + p1.setState(Qt::TouchPointReleased); + nativeTouchPoints = + QWindowSystemInterfacePrivate::toNativeTouchPoints(rawTouchPoints, window); + QWindowSystemInterface::handleTouchEvent(window, 0, touchScreenDevice, nativeTouchPoints); + QCoreApplication::processEvents(); + QVERIFY(touchWidget.seenTouchBegin); + QVERIFY(touchWidget.seenTouchUpdate); + QVERIFY(touchWidget.seenTouchEnd); + QCOMPARE(touchWidget.touchUpdatePoints.count(), 2); + QCOMPARE(touchWidget.touchUpdatePoints[0].id(), initialTouchPointId); + QCOMPARE(touchWidget.touchUpdatePoints[1].id(), initialTouchPointId + 2); +} + void tst_QTouchEvent::deleteInEventHandler() { if (!QGuiApplication::platformName().compare(QLatin1String("wayland"), Qt::CaseInsensitive)) diff --git a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp index 6ec0268d96..4fc18be3d2 100644 --- a/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp +++ b/tests/auto/gui/kernel/qwindow/tst_qwindow.cpp @@ -65,6 +65,7 @@ private slots: void positioningDuringMinimized(); void childWindowPositioning_data(); void childWindowPositioning(); + void childWindowLevel(); void platformSurface(); void isExposed(); void isActive(); @@ -101,6 +102,7 @@ private slots: void initTestCase(); void stateChange_data(); void stateChange(); + void flags(); void cleanup(); private: @@ -596,6 +598,29 @@ void tst_QWindow::childWindowPositioning() QCOMPARE(childWindowAfter.framePosition(), topLeftOrigin); } +void tst_QWindow::childWindowLevel() +{ + ColoredWindow topLevel(Qt::green); + topLevel.setObjectName("topLevel"); + ColoredWindow yellowChild(Qt::yellow, &topLevel); + yellowChild.setObjectName("yellowChild"); + ColoredWindow redChild(Qt::red, &topLevel); + redChild.setObjectName("redChild"); + ColoredWindow blueChild(Qt::blue, &topLevel); + blueChild.setObjectName("blueChild"); + + const QObjectList &siblings = topLevel.children(); + + QCOMPARE(siblings.constFirst(), &yellowChild); + QCOMPARE(siblings.constLast(), &blueChild); + + yellowChild.raise(); + QCOMPARE(siblings.constLast(), &yellowChild); + + blueChild.lower(); + QCOMPARE(siblings.constFirst(), &blueChild); +} + // QTBUG-49709: Verify that the normal geometry is correctly restored // when executing a sequence of window state changes. So far, Windows // only where state changes have immediate effect. @@ -2170,6 +2195,18 @@ void tst_QWindow::requestUpdate() QTRY_COMPARE(window.received(QEvent::UpdateRequest), 2); } +void tst_QWindow::flags() +{ + Window window; + const auto baseFlags = window.flags(); + window.setFlags(window.flags() | Qt::FramelessWindowHint); + QCOMPARE(window.flags(), baseFlags | Qt::FramelessWindowHint); + window.setFlag(Qt::WindowStaysOnTopHint, true); + QCOMPARE(window.flags(), baseFlags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); + window.setFlag(Qt::FramelessWindowHint, false); + QCOMPARE(window.flags(), baseFlags | Qt::WindowStaysOnTopHint); +} + #include <tst_qwindow.moc> QTEST_MAIN(tst_QWindow) diff --git a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp index 9dd9ab05e8..1ce7e797fc 100644 --- a/tests/auto/gui/painting/qcolor/tst_qcolor.cpp +++ b/tests/auto/gui/painting/qcolor/tst_qcolor.cpp @@ -33,6 +33,7 @@ #include <qcolor.h> #include <qdebug.h> +#include <private/qcolorprofile_p.h> #include <private/qdrawingprimitive_sse2_p.h> #include <qrgba64.h> @@ -107,6 +108,9 @@ private slots: void qrgba64Premultiply(); void qrgba64Equivalence(); + void qcolorprofile_data(); + void qcolorprofile(); + #if 0 // Used to be included in Qt4 for Q_WS_X11 void setallowX11ColorNames(); #endif @@ -1587,5 +1591,36 @@ void tst_QColor::qrgba64Equivalence() } } +void tst_QColor::qcolorprofile_data() +{ + QTest::addColumn<qreal>("gammaC"); + QTest::addColumn<int>("tolerance"); + + QTest::newRow("gamma=1.0") << qreal(1.0) << 0; + QTest::newRow("gamma=1.5") << qreal(1.5) << 1; + QTest::newRow("gamma=1.7") << qreal(1.7) << 2; + QTest::newRow("gamma=2.0") << qreal(2.0) << 8; + QTest::newRow("gamma=2.31") << qreal(2.31) << 33; + QTest::newRow("SRgb") << qreal(0.0) << 7; +} + +void tst_QColor::qcolorprofile() +{ + QFETCH(qreal, gammaC); + QFETCH(int, tolerance); + QColorProfile *cp = (gammaC == 0) ? QColorProfile::fromSRgb(): QColorProfile::fromGamma(gammaC); + + // Test we are accurate for most values after converting through gamma-correction. + int error = 0; + for (uint i = 0; i < 256; i++) { + QRgb cin = qRgb(i, i, i); + QRgba64 tmp = cp->toLinear64(cin); + QRgb cout = cp->fromLinear64(tmp); + error += qAbs(qRed(cin) - qRed(cout)); + } + QVERIFY(error <= tolerance); + delete cp; +} + QTEST_MAIN(tst_QColor) #include "tst_qcolor.moc" diff --git a/tests/auto/gui/painting/qpainter/tst_qpainter.cpp b/tests/auto/gui/painting/qpainter/tst_qpainter.cpp index cf4979e291..3562bc63f4 100644 --- a/tests/auto/gui/painting/qpainter/tst_qpainter.cpp +++ b/tests/auto/gui/painting/qpainter/tst_qpainter.cpp @@ -4843,6 +4843,18 @@ void tst_QPainter::blendARGBonRGB_data() << QPainter::CompositionMode_SourceIn << qRgba(255, 0, 0, 127) << 127; QTest::newRow("ARGB_PM source-in RGBx8888") << QImage::Format_RGBX8888 << QImage::Format_ARGB32_Premultiplied << QPainter::CompositionMode_SourceIn << qRgba(127, 0, 0, 127) << 127; + QTest::newRow("ARGB over RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32 + << QPainter::CompositionMode_SourceOver << qRgba(255, 0, 0, 127) << 127; + QTest::newRow("ARGB_PM over RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32_Premultiplied + << QPainter::CompositionMode_SourceOver << qRgba(127, 0, 0, 127) << 127; + QTest::newRow("ARGB source RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32 + << QPainter::CompositionMode_Source << qRgba(255, 0, 0, 127) << 255; + QTest::newRow("ARGB_PM source RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32_Premultiplied + << QPainter::CompositionMode_Source << qRgba(127, 0, 0, 127) << 255; + QTest::newRow("ARGB source-in RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32 + << QPainter::CompositionMode_SourceIn << qRgba(255, 0, 0, 127) << 255; + QTest::newRow("ARGB_PM source-in RGBA8888") << QImage::Format_RGBA8888 << QImage::Format_ARGB32_Premultiplied + << QPainter::CompositionMode_SourceIn << qRgba(127, 0, 0, 127) << 255; QTest::newRow("ARGB over RGB16") << QImage::Format_RGB16 << QImage::Format_ARGB32 << QPainter::CompositionMode_SourceOver << qRgba(255, 0, 0, 127) << 123; QTest::newRow("ARGB_PM over RGB16") << QImage::Format_RGB16 << QImage::Format_ARGB32_Premultiplied @@ -4905,7 +4917,7 @@ void tst_QPainter::blendARGBonRGB() painter.drawImage(0, 0, imageArgb); painter.end(); - QCOMPARE(qRed(imageRgb.pixel(0,0)), expected_red); + QCOMPARE(imageRgb.pixelColor(0,0).red(), expected_red); } enum CosmeticStrokerPaint diff --git a/tests/auto/gui/qopengl/tst_qopengl.cpp b/tests/auto/gui/qopengl/tst_qopengl.cpp index 44921f68aa..7451ef92ee 100644 --- a/tests/auto/gui/qopengl/tst_qopengl.cpp +++ b/tests/auto/gui/qopengl/tst_qopengl.cpp @@ -86,6 +86,7 @@ private slots: void fboMRT_differentFormats(); void openGLPaintDevice_data(); void openGLPaintDevice(); + void openGLPaintDeviceWithChangingContext(); void aboutToBeDestroyed(); void sizeLessWindow(); void QTBUG15621_triangulatingStrokerDivZero(); @@ -948,6 +949,14 @@ void tst_QOpenGL::openGLPaintDevice_data() QTest::newRow("Using QOffscreenSurface - RGB16") << int(QSurface::Offscreen) << QImage::Format_RGB16; } +static void drawColoredRects(QPainter *p, const QSize &size) +{ + p->fillRect(0, 0, size.width() / 2, size.height() / 2, Qt::red); + p->fillRect(size.width() / 2, 0, size.width() / 2, size.height() / 2, Qt::green); + p->fillRect(size.width() / 2, size.height() / 2, size.width() / 2, size.height() / 2, Qt::blue); + p->fillRect(0, size.height() / 2, size.width() / 2, size.height() / 2, Qt::white); +} + void tst_QOpenGL::openGLPaintDevice() { #if defined(Q_OS_LINUX) && defined(Q_CC_GNU) && !defined(__x86_64__) @@ -970,10 +979,7 @@ void tst_QOpenGL::openGLPaintDevice() QImage image(size, imageFormat); QPainter p(&image); - p.fillRect(0, 0, image.width() / 2, image.height() / 2, Qt::red); - p.fillRect(image.width() / 2, 0, image.width() / 2, image.height() / 2, Qt::green); - p.fillRect(image.width() / 2, image.height() / 2, image.width() / 2, image.height() / 2, Qt::blue); - p.fillRect(0, image.height() / 2, image.width() / 2, image.height() / 2, Qt::white); + drawColoredRects(&p, image.size()); p.end(); QOpenGLFramebufferObject fbo(size); @@ -981,10 +987,7 @@ void tst_QOpenGL::openGLPaintDevice() QOpenGLPaintDevice device(size); QVERIFY(p.begin(&device)); - p.fillRect(0, 0, image.width() / 2, image.height() / 2, Qt::red); - p.fillRect(image.width() / 2, 0, image.width() / 2, image.height() / 2, Qt::green); - p.fillRect(image.width() / 2, image.height() / 2, image.width() / 2, image.height() / 2, Qt::blue); - p.fillRect(0, image.height() / 2, image.width() / 2, image.height() / 2, Qt::white); + drawColoredRects(&p, image.size()); p.end(); QImage actual = fbo.toImage().convertToFormat(imageFormat); @@ -1010,6 +1013,59 @@ void tst_QOpenGL::openGLPaintDevice() QCOMPARE(image, actual); } +void tst_QOpenGL::openGLPaintDeviceWithChangingContext() +{ + QScopedPointer<QSurface> surface(createSurface(QSurface::Window)); + const QSize size(512, 512); + + // QOpenGLPaintDevice has a thread-local paint engine. Therefore render + // twice, with a different context and device. Under the hood it will + // still use the same paint engine! + + QOpenGLContext ctx; + QVERIFY(ctx.create()); + QVERIFY(ctx.makeCurrent(surface.data())); + + QOpenGLFramebufferObject fbo(size); + QVERIFY(fbo.bind()); + + QOpenGLPaintDevice device(size); + + QPainter p; + QVERIFY(p.begin(&device)); + drawColoredRects(&p, size); + p.end(); + + QImage img1 = fbo.toImage(); + + QOpenGLContext ctx2; + // When supported, test the special case, where the second context is + // totally incompatible due to being a core profile one. + QSurfaceFormat coreFormat; + coreFormat.setVersion(3, 2); + coreFormat.setProfile(QSurfaceFormat::CoreProfile); + ctx2.setFormat(coreFormat); + if (!ctx2.create() || !ctx2.makeCurrent(surface.data())) { + ctx2.setFormat(QSurfaceFormat()); + QVERIFY(ctx2.create()); + } + + QVERIFY(ctx2.makeCurrent(surface.data())); + + QOpenGLFramebufferObject fbo2(size); + QVERIFY(fbo2.bind()); + + QOpenGLPaintDevice device2(size); + + QVERIFY(p.begin(&device2)); + drawColoredRects(&p, size); + p.end(); + + QImage img2 = fbo2.toImage(); + + QFUZZY_COMPARE_IMAGES(img1, img2); +} + void tst_QOpenGL::aboutToBeDestroyed() { QWindow window; diff --git a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp index de5b2a8676..ef1ad76161 100644 --- a/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp +++ b/tests/auto/gui/text/qtextdocument/tst_qtextdocument.cpp @@ -135,6 +135,7 @@ private slots: void setPlainText(); void toPlainText(); + void toRawText(); void deleteTextObjectsOnClear(); @@ -2396,6 +2397,16 @@ void tst_QTextDocument::toPlainText() QCOMPARE(doc->toPlainText(), QLatin1String("Hello World")); } +void tst_QTextDocument::toRawText() +{ + doc->setHtml(" "); + + QString rawText = doc->toRawText(); + QCOMPARE(rawText.size(), 1); + QCOMPARE(rawText.at(0).unicode(), ushort(QChar::Nbsp)); +} + + void tst_QTextDocument::deleteTextObjectsOnClear() { QPointer<QTextTable> table = cursor.insertTable(2, 2); diff --git a/tests/auto/network/access/access.pro b/tests/auto/network/access/access.pro index 1d78cf253b..b140b5e9f2 100644 --- a/tests/auto/network/access/access.pro +++ b/tests/auto/network/access/access.pro @@ -13,11 +13,13 @@ SUBDIRS=\ qhttpnetworkreply \ qabstractnetworkcache \ hpack \ - http2 + http2 \ + hsts !qtConfig(private_tests): SUBDIRS -= \ qhttpnetworkconnection \ qhttpnetworkreply \ qftp \ hpack \ - http2 + http2 \ + hsts diff --git a/tests/auto/network/access/hsts/hsts.pro b/tests/auto/network/access/hsts/hsts.pro new file mode 100644 index 0000000000..07bdea5f62 --- /dev/null +++ b/tests/auto/network/access/hsts/hsts.pro @@ -0,0 +1,6 @@ +QT += core core-private network network-private testlib +CONFIG += testcase parallel_test c++11 +TEMPLATE = app +TARGET = tst_qhsts + +SOURCES += tst_qhsts.cpp diff --git a/tests/auto/network/access/hsts/tst_qhsts.cpp b/tests/auto/network/access/hsts/tst_qhsts.cpp new file mode 100644 index 0000000000..656516f46b --- /dev/null +++ b/tests/auto/network/access/hsts/tst_qhsts.cpp @@ -0,0 +1,318 @@ +/**************************************************************************** +** +** 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/qdatetime.h> +#include <QtCore/qvector.h> +#include <QtCore/qpair.h> +#include <QtCore/qurl.h> + +#include <QtNetwork/private/qhsts_p.h> + +QT_USE_NAMESPACE + +class tst_QHsts : public QObject +{ + Q_OBJECT +private Q_SLOTS: + void testSingleKnownHost_data(); + void testSingleKnownHost(); + void testMultilpeKnownHosts(); + void testPolicyExpiration(); + void testSTSHeaderParser(); +}; + +void tst_QHsts::testSingleKnownHost_data() +{ + QTest::addColumn<QUrl>("knownHost"); + QTest::addColumn<QDateTime>("policyExpires"); + QTest::addColumn<bool>("includeSubDomains"); + QTest::addColumn<QUrl>("hostToTest"); + QTest::addColumn<bool>("isKnown"); + + const QDateTime currentUTC = QDateTime::currentDateTimeUtc(); + const QUrl knownHost(QLatin1String("http://example.com")); + const QUrl validSubdomain(QLatin1String("https://sub.example.com/ohoho")); + const QUrl unknownDomain(QLatin1String("http://example.org")); + const QUrl subSubdomain(QLatin1String("https://level3.level2.example.com")); + + const QDateTime validDate(currentUTC.addSecs(1000)); + QTest::newRow("same-known") << knownHost << validDate << false << knownHost << true; + QTest::newRow("subexcluded") << knownHost << validDate << false << validSubdomain << false; + QTest::newRow("subincluded") << knownHost << validDate << true << validSubdomain << true; + QTest::newRow("unknown-subexcluded") << knownHost << validDate << false << unknownDomain << false; + QTest::newRow("unknown-subincluded") << knownHost << validDate << true << unknownDomain << false; + QTest::newRow("sub-subdomain-subincluded") << knownHost << validDate << true << subSubdomain << true; + QTest::newRow("sub-subdomain-subexcluded") << knownHost << validDate << false << subSubdomain << false; + + const QDateTime invalidDate; + QTest::newRow("invalid-time") << knownHost << invalidDate << false << knownHost << false; + QTest::newRow("invalid-time-subexcluded") << knownHost << invalidDate << false + << validSubdomain << false; + QTest::newRow("invalid-time-subincluded") << knownHost << invalidDate << true + << validSubdomain << false; + + const QDateTime expiredDate(currentUTC.addSecs(-1000)); + QTest::newRow("expired-time") << knownHost << expiredDate << false << knownHost << false; + QTest::newRow("expired-time-subexcluded") << knownHost << expiredDate << false + << validSubdomain << false; + QTest::newRow("expired-time-subincluded") << knownHost << expiredDate << true + << validSubdomain << false; + const QUrl ipAsHost(QLatin1String("http://127.0.0.1")); + QTest::newRow("ip-address-in-hostname") << ipAsHost << validDate << false + << ipAsHost << false; + + const QUrl anyIPv4AsHost(QLatin1String("http://0.0.0.0")); + QTest::newRow("anyip4-address-in-hostname") << anyIPv4AsHost << validDate + << false << anyIPv4AsHost << false; + const QUrl anyIPv6AsHost(QLatin1String("http://[::]")); + QTest::newRow("anyip6-address-in-hostname") << anyIPv6AsHost << validDate + << false << anyIPv6AsHost << false; + +} + +void tst_QHsts::testSingleKnownHost() +{ + QFETCH(const QUrl, knownHost); + QFETCH(const QDateTime, policyExpires); + QFETCH(const bool, includeSubDomains); + QFETCH(const QUrl, hostToTest); + QFETCH(const bool, isKnown); + + QHstsCache cache; + cache.updateKnownHost(knownHost, policyExpires, includeSubDomains); + QCOMPARE(cache.isKnownHost(hostToTest), isKnown); +} + +void tst_QHsts::testMultilpeKnownHosts() +{ + const QDateTime currentUTC = QDateTime::currentDateTimeUtc(); + const QDateTime validDate(currentUTC.addSecs(10000)); + const QDateTime expiredDate(currentUTC.addSecs(-10000)); + const QUrl exampleCom(QLatin1String("https://example.com")); + const QUrl subExampleCom(QLatin1String("https://sub.example.com")); + + QHstsCache cache; + // example.com is HSTS and includes subdomains: + cache.updateKnownHost(exampleCom, validDate, true); + QVERIFY(cache.isKnownHost(exampleCom)); + QVERIFY(cache.isKnownHost(subExampleCom)); + // example.com can set its policy not to include subdomains: + cache.updateKnownHost(exampleCom, validDate, false); + QVERIFY(!cache.isKnownHost(subExampleCom)); + // but sub.example.com can set its own policy: + cache.updateKnownHost(subExampleCom, validDate, false); + QVERIFY(cache.isKnownHost(subExampleCom)); + // let's say example.com's policy has expired: + cache.updateKnownHost(exampleCom, expiredDate, false); + QVERIFY(!cache.isKnownHost(exampleCom)); + // it should not affect sub.example.com's policy: + QVERIFY(cache.isKnownHost(subExampleCom)); + + // clear cache and invalidate all policies: + cache.clear(); + QVERIFY(!cache.isKnownHost(exampleCom)); + QVERIFY(!cache.isKnownHost(subExampleCom)); + + // siblings: + const QUrl anotherSub(QLatin1String("https://sub2.example.com")); + cache.updateKnownHost(subExampleCom, validDate, true); + cache.updateKnownHost(anotherSub, validDate, true); + QVERIFY(cache.isKnownHost(subExampleCom)); + QVERIFY(cache.isKnownHost(anotherSub)); + // they cannot set superdomain's policy: + QVERIFY(!cache.isKnownHost(exampleCom)); + // a sibling cannot set another sibling's policy: + cache.updateKnownHost(anotherSub, expiredDate, false); + QVERIFY(cache.isKnownHost(subExampleCom)); + QVERIFY(!cache.isKnownHost(anotherSub)); + QVERIFY(!cache.isKnownHost(exampleCom)); + // let's make example.com known again: + cache.updateKnownHost(exampleCom, validDate, true); + // a subdomain cannot affect its superdomain's policy: + cache.updateKnownHost(subExampleCom, expiredDate, true); + QVERIFY(cache.isKnownHost(exampleCom)); + // and this superdomain includes subdomains in its HSTS policy: + QVERIFY(cache.isKnownHost(subExampleCom)); + QVERIFY(cache.isKnownHost(anotherSub)); + + // a subdomain (with its subdomains) cannot affect its superdomain's policy: + cache.updateKnownHost(exampleCom, expiredDate, true); + cache.updateKnownHost(subExampleCom, validDate, true); + QVERIFY(cache.isKnownHost(subExampleCom)); + QVERIFY(!cache.isKnownHost(exampleCom)); +} + +void tst_QHsts::testPolicyExpiration() +{ + QDateTime currentUTC = QDateTime::currentDateTimeUtc(); + const QUrl exampleCom(QLatin1String("http://example.com")); + const QUrl subdomain(QLatin1String("http://subdomain.example.com")); + const qint64 lifeTimeMS = 50; + + QHstsCache cache; + // start with 'includeSubDomains' and 5 s. lifetime: + cache.updateKnownHost(exampleCom, currentUTC.addMSecs(lifeTimeMS), true); + QVERIFY(cache.isKnownHost(exampleCom)); + QVERIFY(cache.isKnownHost(subdomain)); + // wait for approx. a half of lifetime: + QTest::qWait(lifeTimeMS / 2); + + if (QDateTime::currentDateTimeUtc() < currentUTC.addMSecs(lifeTimeMS)) { + // Should still be valid: + QVERIFY(cache.isKnownHost(exampleCom)); + QVERIFY(cache.isKnownHost(subdomain)); + } + + QTest::qWait(lifeTimeMS); + // expired: + QVERIFY(!cache.isKnownHost(exampleCom)); + QVERIFY(!cache.isKnownHost(subdomain)); + + // now check that superdomain's policy expires, but not subdomain's policy: + currentUTC = QDateTime::currentDateTimeUtc(); + cache.updateKnownHost(exampleCom, currentUTC.addMSecs(lifeTimeMS / 5), true); + cache.updateKnownHost(subdomain, currentUTC.addMSecs(lifeTimeMS), true); + QVERIFY(cache.isKnownHost(exampleCom)); + QVERIFY(cache.isKnownHost(subdomain)); + QTest::qWait(lifeTimeMS / 2); + if (QDateTime::currentDateTimeUtc() < currentUTC.addMSecs(lifeTimeMS)) { + QVERIFY(!cache.isKnownHost(exampleCom)); + QVERIFY(cache.isKnownHost(subdomain)); + } +} + +void tst_QHsts::testSTSHeaderParser() +{ + QHstsHeaderParser parser; + using Header = QPair<QByteArray, QByteArray>; + using Headers = QList<Header>; + + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + Headers list; + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + list << Header("Strict-Transport-security", "200"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + // This header is missing REQUIRED max-age directive, so we'll ignore it: + list << Header("Strict-Transport-Security", "includeSubDomains"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + list.pop_back(); + list << Header("Strict-Transport-Security", "includeSubDomains;max-age=1000"); + QVERIFY(parser.parse(list)); + QVERIFY(parser.expirationDate() > QDateTime::currentDateTimeUtc()); + QVERIFY(parser.includeSubDomains()); + + list.pop_back(); + // Invalid (includeSubDomains twice): + list << Header("Strict-Transport-Security", "max-age = 1000 ; includeSubDomains;includeSubDomains"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + list.pop_back(); + // Invalid (weird number of seconds): + list << Header("Strict-Transport-Security", "max-age=-1000 ; includeSubDomains"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + list.pop_back(); + // Note, directives are case-insensitive + we should ignore unknown directive. + list << Header("Strict-Transport-Security", ";max-age=1000 ;includesubdomains;;" + "nowsomeunknownheader=\"somevaluewithescapes\\;\""); + QVERIFY(parser.parse(list)); + QVERIFY(parser.includeSubDomains()); + QVERIFY(parser.expirationDate().isValid()); + + list.pop_back(); + // Check that we know how to unescape max-age: + list << Header("Strict-Transport-Security", "max-age=\"1000\""); + QVERIFY(parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(parser.expirationDate().isValid()); + + list.pop_back(); + // The only STS header, with invalid syntax though, to be ignored: + list << Header("Strict-Transport-Security", "max-age; max-age=15768000"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); + + // Now we check that our parse chosses the first valid STS header and ignores + // others: + list.clear(); + list << Header("Strict-Transport-Security", "includeSubdomains; max-age=\"hehehe\";"); + list << Header("Strict-Transport-Security", "max-age=10101"); + QVERIFY(parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(parser.expirationDate().isValid()); + + + list.clear(); + list << Header("Strict-Transport-Security", "max-age=0"); + QVERIFY(parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(parser.expirationDate() <= QDateTime::currentDateTimeUtc()); + + // Parsing is case-insensitive: + list.pop_back(); + list << Header("Strict-Transport-Security", "Max-aGE=1000; InclUdesUbdomains"); + QVERIFY(parser.parse(list)); + QVERIFY(parser.includeSubDomains()); + QVERIFY(parser.expirationDate().isValid()); + + // Grammar of STS header is quite permissive, let's check we can parse + // some weird but valid header: + list.pop_back(); + list << Header("Strict-Transport-Security", ";;; max-age = 17; ; ; ; ;;; ;;" + ";;; ; includeSubdomains ;;thisIsUnknownDirective;;;;"); + QVERIFY(parser.parse(list)); + QVERIFY(parser.includeSubDomains()); + QVERIFY(parser.expirationDate().isValid()); + + list.pop_back(); + list << Header("Strict-Transport-Security", "max-age=1000; includeSubDomains bogon"); + QVERIFY(!parser.parse(list)); + QVERIFY(!parser.includeSubDomains()); + QVERIFY(!parser.expirationDate().isValid()); +} + +QTEST_MAIN(tst_QHsts) + +#include "tst_qhsts.moc" diff --git a/tests/auto/network/access/http2/http2srv.cpp b/tests/auto/network/access/http2/http2srv.cpp index 9d68b5c798..9f77419461 100644 --- a/tests/auto/network/access/http2/http2srv.cpp +++ b/tests/auto/network/access/http2/http2srv.cpp @@ -41,6 +41,7 @@ #include <QtNetwork/qtcpsocket.h> +#include <QtCore/qtimer.h> #include <QtCore/qdebug.h> #include <QtCore/qlist.h> #include <QtCore/qfile.h> @@ -117,6 +118,13 @@ void Http2Server::setResponseBody(const QByteArray &body) responseBody = body; } +void Http2Server::emulateGOAWAY(int timeout) +{ + Q_ASSERT(timeout >= 0); + testingGOAWAY = true; + goawayTimeout = timeout; +} + void Http2Server::startServer() { #ifdef QT_NO_SSL @@ -271,6 +279,16 @@ void Http2Server::connectionEstablished() { using namespace Http2; + if (testingGOAWAY) { + auto timer = new QTimer(this); + timer->setSingleShot(true); + connect(timer, &QTimer::timeout, [this]() { + sendGOAWAY(quint32(connectionStreamID), quint32(INTERNAL_ERROR), 0); + }); + timer->start(goawayTimeout); + return; + } + connect(socket.data(), SIGNAL(readyRead()), this, SLOT(readReady())); diff --git a/tests/auto/network/access/http2/http2srv.h b/tests/auto/network/access/http2/http2srv.h index 15a4f212c9..63a4a4c8e9 100644 --- a/tests/auto/network/access/http2/http2srv.h +++ b/tests/auto/network/access/http2/http2srv.h @@ -70,6 +70,7 @@ public: // To be called before server started: void enablePushPromise(bool enabled, const QByteArray &path = QByteArray()); void setResponseBody(const QByteArray &body); + void emulateGOAWAY(int timeout); // Invokables, since we can call them from the main thread, // but server (can) work on its own thread. @@ -162,6 +163,9 @@ private: quint32 lastPromisedStream = 0; QByteArray pushPath; + bool testingGOAWAY = false; + int goawayTimeout = 0; + protected slots: void ignoreErrorSlot(); }; diff --git a/tests/auto/network/access/http2/tst_http2.cpp b/tests/auto/network/access/http2/tst_http2.cpp index 771ddb01be..645d28ccb3 100644 --- a/tests/auto/network/access/http2/tst_http2.cpp +++ b/tests/auto/network/access/http2/tst_http2.cpp @@ -69,6 +69,8 @@ private slots: void flowControlClientSide(); void flowControlServerSide(); void pushPromise(); + void goaway_data(); + void goaway(); protected slots: // Slots to listen to our in-process server: @@ -83,6 +85,7 @@ protected slots: void receivedData(quint32 streamID); void windowUpdated(quint32 streamID); void replyFinished(); + void replyFinishedWithError(); private: void clearHTTP2State(); @@ -97,6 +100,7 @@ private: void sendRequest(int streamNumber, QNetworkRequest::Priority priority = QNetworkRequest::NormalPriority, const QByteArray &payload = QByteArray()); + QUrl requestUrl() const; quint16 serverPort = 0; QThread *workerThread = nullptr; @@ -196,9 +200,8 @@ void tst_Http2::singleRequest() QVERIFY(serverPort != 0); - const QString urlAsString(clearTextHTTP2 ? QString("http://127.0.0.1:%1/index.html") - : QString("https://127.0.0.1:%1/index.html")); - const QUrl url(urlAsString.arg(serverPort)); + auto url = requestUrl(); + url.setPath("/index.html"); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); @@ -347,11 +350,10 @@ void tst_Http2::pushPromise() QVERIFY(serverPort != 0); - const QString urlAsString((clearTextHTTP2 ? QString("http://127.0.0.1:%1/") - : QString("https://127.0.0.1:%1/")).arg(serverPort)); - const QUrl requestUrl(urlAsString + "index.html"); + auto url = requestUrl(); + url.setPath("/index.html"); - QNetworkRequest request(requestUrl); + QNetworkRequest request(url); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); auto reply = manager.get(request); @@ -374,8 +376,8 @@ void tst_Http2::pushPromise() // Create an additional request (let's say, we parsed reply and realized we // need another resource): - const QUrl promisedUrl(urlAsString + "script.js"); - QNetworkRequest promisedRequest(promisedUrl); + url.setPath("/script.js"); + QNetworkRequest promisedRequest(url); promisedRequest.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); reply = manager.get(promisedRequest); connect(reply, &QNetworkReply::finished, this, &tst_Http2::replyFinished); @@ -391,6 +393,61 @@ void tst_Http2::pushPromise() QVERIFY(reply->isFinished()); } +void tst_Http2::goaway_data() +{ + // For now we test only basic things in two very simple scenarios: + // - server sends GOAWAY immediately or + // - server waits for some time (enough for ur to init several streams on a + // client side); then suddenly it replies with GOAWAY, never processing any + // request. + QTest::addColumn<int>("responseTimeoutMS"); + QTest::newRow("ImmediateGOAWAY") << 0; + QTest::newRow("DelayedGOAWAY") << 1000; +} + +void tst_Http2::goaway() +{ + using namespace Http2; + + QFETCH(const int, responseTimeoutMS); + + clearHTTP2State(); + + serverPort = 0; + nRequests = 3; + + ServerPtr srv(newServer(defaultServerSettings, defaultClientSettings)); + srv->emulateGOAWAY(responseTimeoutMS); + QMetaObject::invokeMethod(srv.data(), "startServer", Qt::QueuedConnection); + runEventLoop(); + + QVERIFY(serverPort != 0); + + auto url = requestUrl(); + // We have to store these replies, so that we can check errors later. + std::vector<QNetworkReply *> replies(nRequests); + for (int i = 0; i < nRequests; ++i) { + url.setPath(QString("/%1").arg(i)); + QNetworkRequest request(url); + request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); + replies[i] = manager.get(request); + QCOMPARE(replies[i]->error(), QNetworkReply::NoError); + void (QNetworkReply::*errorSignal)(QNetworkReply::NetworkError) = + &QNetworkReply::error; + connect(replies[i], errorSignal, this, &tst_Http2::replyFinishedWithError); + // Since we're using self-signed certificates, ignore SSL errors: + replies[i]->ignoreSslErrors(); + } + + runEventLoop(5000 + responseTimeoutMS); + + // No request processed, no 'replyFinished' slot calls: + QCOMPARE(nRequests, 0); + // Our server did not bother to send anything except a single GOAWAY frame: + QVERIFY(!prefaceOK); + QVERIFY(!serverGotSettingsACK); +} + void tst_Http2::serverStarted(quint16 port) { serverPort = port; @@ -445,10 +502,9 @@ void tst_Http2::sendRequest(int streamNumber, QNetworkRequest::Priority priority, const QByteArray &payload) { - static const QString urlAsString(clearTextHTTP2 ? "http://127.0.0.1:%1/stream%2.html" - : "https://127.0.0.1:%1/stream%2.html"); + auto url = requestUrl(); + url.setPath(QString("/stream%1.html").arg(streamNumber)); - const QUrl url(urlAsString.arg(serverPort).arg(streamNumber)); QNetworkRequest request(url); request.setAttribute(QNetworkRequest::HTTP2AllowedAttribute, QVariant(true)); request.setPriority(priority); @@ -463,6 +519,14 @@ void tst_Http2::sendRequest(int streamNumber, connect(reply, &QNetworkReply::finished, this, &tst_Http2::replyFinished); } +QUrl tst_Http2::requestUrl() const +{ + static auto url = QUrl(QLatin1String(clearTextHTTP2 ? "http://127.0.0.1" : "https://127.0.0.1")); + url.setPort(serverPort); + + return url; +} + void tst_Http2::clientPrefaceOK() { prefaceOK = true; @@ -532,6 +596,21 @@ void tst_Http2::replyFinished() stopEventLoop(); } +void tst_Http2::replyFinishedWithError() +{ + QVERIFY(nRequests); + + if (const auto reply = qobject_cast<QNetworkReply *>(sender())) { + // For now this is a 'generic' code, it just verifies some error was + // reported without testing its type. + QVERIFY(reply->error() != QNetworkReply::NoError); + } + + --nRequests; + if (!nRequests) + stopEventLoop(); +} + QT_END_NAMESPACE QTEST_MAIN(tst_Http2) diff --git a/tests/auto/network/access/qnetworkreply/test/test.pro b/tests/auto/network/access/qnetworkreply/test/test.pro index 45a5734305..8aeec88fd2 100644 --- a/tests/auto/network/access/qnetworkreply/test/test.pro +++ b/tests/auto/network/access/qnetworkreply/test/test.pro @@ -1,6 +1,6 @@ CONFIG += testcase testcase.timeout = 600 # this test is slow -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target SOURCES += ../tst_qnetworkreply.cpp TARGET = ../tst_qnetworkreply diff --git a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp index 649278d48b..f19ce4ac75 100644 --- a/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp +++ b/tests/auto/network/access/qnetworkreply/tst_qnetworkreply.cpp @@ -104,10 +104,10 @@ class tst_QNetworkReply: public QObject Q_OBJECT #ifndef QT_NO_NETWORKPROXY - struct ProxyData { + struct ProxyData + { ProxyData(const QNetworkProxy &p, const QByteArray &t, bool auth) - : tag(t), proxy(p), requiresAuthentication(auth) - { } + : tag(t), proxy(p), requiresAuthentication(auth) {} QByteArray tag; QNetworkProxy proxy; bool requiresAuthentication; @@ -115,7 +115,8 @@ class tst_QNetworkReply: public QObject #endif // !QT_NO_NETWORKPROXY static bool seedCreated; - static QString createUniqueExtension() { + static QString createUniqueExtension() + { if (!seedCreated) { qsrand(QTime(0,0,0).msecsTo(QTime::currentTime()) + QCoreApplication::applicationPid()); seedCreated = true; // not thread-safe, but who cares @@ -131,7 +132,9 @@ class tst_QNetworkReply: public QObject "location: %1\r\n" "\r\n"; return s; - }; + } + + static const QByteArray httpEmpty200Response; QEventLoop *loop; enum RunSimpleRequestReturn { Timeout = 0, Success, Failure }; @@ -475,6 +478,12 @@ private Q_SLOTS: void ioHttpChangeMaxRedirects(); void ioHttpRedirectErrors_data(); void ioHttpRedirectErrors(); + void ioHttpRedirectPolicy_data(); + void ioHttpRedirectPolicy(); + void ioHttpRedirectPolicyErrors_data(); + void ioHttpRedirectPolicyErrors(); + void ioHttpUserVerifiedRedirect_data(); + void ioHttpUserVerifiedRedirect(); #ifndef QT_NO_SSL void putWithServerClosingConnectionImmediately(); #endif @@ -488,6 +497,8 @@ private: bool notEnoughDataForFastSender; }; +const QByteArray tst_QNetworkReply::httpEmpty200Response = + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; bool tst_QNetworkReply::seedCreated = false; #define RUN_REQUEST(call) \ @@ -495,7 +506,7 @@ bool tst_QNetworkReply::seedCreated = false; QString errorMsg = call; \ if (!errorMsg.isEmpty()) \ QFAIL(qPrintable(errorMsg)); \ - } while (0); + } while (0) #ifndef QT_NO_SSL static void setupSslServer(QSslSocket* serverSocket) @@ -507,6 +518,7 @@ static void setupSslServer(QSslSocket* serverSocket) serverSocket->setProtocol(QSsl::AnyProtocol); serverSocket->setLocalCertificate(testDataDir + "/certs/server.pem"); serverSocket->setPrivateKey(testDataDir + "/certs/server.key"); + serverSocket->startServerEncryption(); } #endif @@ -553,31 +565,30 @@ protected: void incomingConnection(qintptr socketDescriptor) { //qDebug() << "incomingConnection" << socketDescriptor << "doSsl:" << doSsl << "ipv6:" << ipv6; - if (!doSsl) { - client = new QTcpSocket; - client->setSocketDescriptor(socketDescriptor); - connectSocketSignals(); - } else { #ifndef QT_NO_SSL - QSslSocket *serverSocket = new QSslSocket; - serverSocket->setParent(this); - if (serverSocket->setSocketDescriptor(socketDescriptor)) { - connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>))); - setupSslServer(serverSocket); - serverSocket->startServerEncryption(); - client = serverSocket; - connectSocketSignals(); - } else { + if (doSsl) { + QSslSocket *serverSocket = new QSslSocket(this); + if (!serverSocket->setSocketDescriptor(socketDescriptor)) { delete serverSocket; return; } + connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>))); + // connect(serverSocket, &QSslSocket::encrypted, this, &SslServer::ready); ? + setupSslServer(serverSocket); + client = serverSocket; + } else #endif + { + client = new QTcpSocket; + client->setSocketDescriptor(socketDescriptor); } + connectSocketSignals(); client->setParent(this); ++totalConnections; } - virtual void reply() { + virtual void reply() + { Q_ASSERT(!client.isNull()); // we need to emulate the bytesWrittenSlot call if the data is empty. if (dataToTransmit.size() == 0) { @@ -634,7 +645,8 @@ public slots: } } - void bytesWrittenSlot() { + void bytesWrittenSlot() + { Q_ASSERT(!client.isNull()); // Disconnect and delete in next cycle (else Windows clients will fail with RemoteHostClosedError). if (doClose && client->bytesToWrite() == 0) { @@ -879,7 +891,8 @@ class BlockingTcpServer : public QTcpServer public: BlockingTcpServer(bool ssl) : doSsl(ssl), sslSocket(0) {} - QTcpSocket* waitForNextConnectionSocket() { + QTcpSocket* waitForNextConnectionSocket() + { waitForNewConnection(-1); if (doSsl) { if (!sslSocket) @@ -900,7 +913,6 @@ public: serverSocket->setSocketDescriptor(socketDescriptor); connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(slotSslErrors(QList<QSslError>))); setupSslServer(serverSocket); - serverSocket->startServerEncryption(); sslSocket = serverSocket; } else #endif @@ -1381,14 +1393,12 @@ static QByteArray msgWaitForFinished(QNetworkReplyPtr &reply) QString result; QDebug debug(&result); debug << reply->url(); - if (reply->isFinished()) { - if (reply->error() == QNetworkReply::NoError) - debug << "finished."; - else - debug << "failed: #" << reply->error() << reply->errorString(); - } else { + if (!reply->isFinished()) debug << "timed out."; - } + else if (reply->error() == QNetworkReply::NoError) + debug << "finished."; + else + debug << "failed: #" << reply->error() << reply->errorString(); return result.toLocal8Bit(); } @@ -1403,7 +1413,7 @@ int tst_QNetworkReply::waitForFinish(QNetworkReplyPtr &reply) QSignalSpy spy(reply.data(), SIGNAL(downloadProgress(qint64,qint64))); while (!reply->isFinished()) { QTimer::singleShot(5000, loop, SLOT(quit())); - if ( loop->exec() == Timeout && count == spy.count() && !reply->isFinished()) { + if (loop->exec() == Timeout && count == spy.count() && !reply->isFinished()) { returnCode = Timeout; break; } @@ -1417,12 +1427,14 @@ int tst_QNetworkReply::waitForFinish(QNetworkReplyPtr &reply) void tst_QNetworkReply::finished() { - loop->exit(returnCode = Success); + if (loop) + loop->exit(returnCode = Success); } void tst_QNetworkReply::gotError() { - loop->exit(returnCode = Failure); + if (loop) + loop->exit(returnCode = Failure); disconnect(QObject::sender(), SIGNAL(finished()), this, 0); } @@ -4725,11 +4737,13 @@ void tst_QNetworkReply::ioPostToHttpNoBufferFlag() } #ifndef QT_NO_SSL -class SslServer : public QTcpServer { +class SslServer : public QTcpServer +{ Q_OBJECT public: SslServer() : socket(0), m_ssl(true) {} - void incomingConnection(qintptr socketDescriptor) { + void incomingConnection(qintptr socketDescriptor) + { QSslSocket *serverSocket = new QSslSocket; serverSocket->setParent(this); @@ -4739,16 +4753,9 @@ public: emit newPlainConnection(serverSocket); return; } - QString testDataDir = QFileInfo(QFINDTESTDATA("rfc3252.txt")).absolutePath(); - if (testDataDir.isEmpty()) - testDataDir = QCoreApplication::applicationDirPath(); - connect(serverSocket, SIGNAL(encrypted()), this, SLOT(encryptedSlot())); - serverSocket->setProtocol(QSsl::AnyProtocol); connect(serverSocket, SIGNAL(sslErrors(QList<QSslError>)), serverSocket, SLOT(ignoreSslErrors())); - serverSocket->setLocalCertificate(testDataDir + "/certs/server.pem"); - serverSocket->setPrivateKey(testDataDir + "/certs/server.key"); - serverSocket->startServerEncryption(); + setupSslServer(serverSocket); } else { delete serverSocket; } @@ -4757,11 +4764,13 @@ signals: void newEncryptedConnection(QSslSocket *s); void newPlainConnection(QSslSocket *s); public slots: - void encryptedSlot() { + void encryptedSlot() + { socket = (QSslSocket*) sender(); emit newEncryptedConnection(socket); } - void readyReadSlot() { + void readyReadSlot() + { // for the incoming sockets, not the server socket //qDebug() << static_cast<QSslSocket*>(sender())->bytesAvailable() << static_cast<QSslSocket*>(sender())->encryptedBytesAvailable(); } @@ -4807,7 +4816,7 @@ void tst_QNetworkReply::ioPostToHttpsUploadProgress() disconnect(&server, SIGNAL(newEncryptedConnection(QSslSocket*)), &QTestEventLoop::instance(), SLOT(exitLoop())); - incomingSocket->setReadBufferSize(1*1024); + incomingSocket->setReadBufferSize(1024); // some progress should have been made QTRY_VERIFY(!spy.isEmpty()); QList<QVariant> args = spy.last(); @@ -4911,7 +4920,7 @@ void tst_QNetworkReply::ioGetFromBuiltinHttp() QCOMPARE(reply->header(QNetworkRequest::ContentLengthHeader).toLongLong(), (qint64)testData.size()); if (reader.data.size() < testData.size()) { // oops? - QCOMPARE(reader.data, testData.mid(0, reader.data.size())); + QCOMPARE(reader.data, testData.left(reader.data.size())); qDebug() << "The data is incomplete, the last" << testData.size() - reader.data.size() << "bytes are missing"; } QCOMPARE(reader.data.size(), testData.size()); @@ -4958,7 +4967,7 @@ void tst_QNetworkReply::ioPostToHttpUploadProgress() QVERIFY(incomingSocket); disconnect(&server, SIGNAL(newConnection()), &QTestEventLoop::instance(), SLOT(exitLoop())); - incomingSocket->setReadBufferSize(1*1024); + incomingSocket->setReadBufferSize(1024); QTestEventLoop::instance().enterLoop(5); // some progress should have been made QVERIFY(!spy.isEmpty()); @@ -5660,12 +5669,14 @@ void tst_QNetworkReply::httpProxyCommands() QCOMPARE(uaheader, QByteArray("User-Agent: QNetworkReplyAutoTest/1.0")); } -class ProxyChangeHelper : public QObject { +class ProxyChangeHelper : public QObject +{ Q_OBJECT public: ProxyChangeHelper() : QObject(), signalCount(0) {}; public slots: - void finishedSlot() { + void finishedSlot() + { signalCount++; if (signalCount == 2) QMetaObject::invokeMethod(&QTestEventLoop::instance(), "exitLoop", Qt::QueuedConnection); @@ -5911,7 +5922,8 @@ void tst_QNetworkReply::httpReUsingConnectionSequential() reply2->deleteLater(); } -class HttpReUsingConnectionFromFinishedSlot : public QObject { +class HttpReUsingConnectionFromFinishedSlot : public QObject +{ Q_OBJECT public: QNetworkReply* reply1; @@ -5919,7 +5931,8 @@ public: QUrl url; QNetworkAccessManager manager; public slots: - void finishedSlot() { + void finishedSlot() + { QVERIFY(!reply1->error()); QFETCH(bool, doDeleteLater); @@ -5967,7 +5980,8 @@ void tst_QNetworkReply::httpReUsingConnectionFromFinishedSlot() QCOMPARE(server.totalConnections, 1); } -class HttpRecursiveCreationHelper : public QObject { +class HttpRecursiveCreationHelper : public QObject +{ Q_OBJECT public: @@ -5983,7 +5997,8 @@ public: int requestsStartedCount_readyRead; int requestsFinishedCount; public slots: - void finishedSlot() { + void finishedSlot() + { requestsFinishedCount++; QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); @@ -6002,7 +6017,8 @@ public slots: reply->deleteLater(); } - void readyReadSlot() { + void readyReadSlot() + { QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender()); QVERIFY(!reply->error()); @@ -6011,7 +6027,8 @@ public slots: requestsStartedCount_readyRead++; } } - void startOne() { + void startOne() + { QUrl url = "http://" + QtNetworkSettings::serverName() + "/qtest/fluke.gif"; QNetworkRequest request(url); QNetworkReply *reply = manager.get(request); @@ -6380,7 +6397,8 @@ void tst_QNetworkReply::getFromHttpIntoBuffer() } // FIXME we really need to consolidate all those server implementations -class GetFromHttpIntoBuffer2Server : QObject { +class GetFromHttpIntoBuffer2Server : QObject +{ Q_OBJECT qint64 dataSize; qint64 dataSent; @@ -6390,26 +6408,28 @@ class GetFromHttpIntoBuffer2Server : QObject { bool chunkedEncoding; public: - GetFromHttpIntoBuffer2Server (qint64 ds, bool sscl, bool ce) : dataSize(ds), dataSent(0), - client(0), serverSendsContentLength(sscl), chunkedEncoding(ce) { + GetFromHttpIntoBuffer2Server (qint64 ds, bool sscl, bool ce) + : dataSize(ds), dataSent(0), client(0), + serverSendsContentLength(sscl), chunkedEncoding(ce) + { server.listen(); connect(&server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot())); } - int serverPort() { - return server.serverPort(); - } + int serverPort() { return server.serverPort(); } public slots: - void newConnectionSlot() { + void newConnectionSlot() + { client = server.nextPendingConnection(); client->setParent(this); connect(client, SIGNAL(readyRead()), this, SLOT(readyReadSlot())); connect(client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot(qint64))); } - void readyReadSlot() { + void readyReadSlot() + { client->readAll(); client->write("HTTP/1.0 200 OK\n"); if (serverSendsContentLength) @@ -6419,7 +6439,8 @@ public slots: client->write("Connection: close\n\n"); } - void bytesWrittenSlot(qint64 amount) { + void bytesWrittenSlot(qint64 amount) + { Q_UNUSED(amount); if (dataSent == dataSize && client) { // close eventually @@ -6453,7 +6474,8 @@ public slots: } }; -class GetFromHttpIntoBuffer2Client : QObject { +class GetFromHttpIntoBuffer2Client : QObject +{ Q_OBJECT private: bool useDownloadBuffer; @@ -6470,7 +6492,8 @@ public: } public slots: - void metaDataChangedSlot() { + void metaDataChangedSlot() + { if (useDownloadBuffer) { QSharedPointer<char> sharedPointer = qvariant_cast<QSharedPointer<char> >(reply->attribute(QNetworkRequest::DownloadBufferAttribute)); QVERIFY(!sharedPointer.isNull()); // It will be 0 if it failed @@ -6480,7 +6503,8 @@ public: QVERIFY(bytesAvailableList.isEmpty()); } - void readyReadSlot() { + void readyReadSlot() + { QVERIFY(!reply->isFinished()); qint64 bytesAvailable = reply->bytesAvailable(); @@ -6502,7 +6526,8 @@ public: // Add bytesAvailable to a list an parse } - void finishedSlot() { + void finishedSlot() + { // We should have already received all readyRead QVERIFY(!bytesAvailableList.isEmpty()); QCOMPARE(bytesAvailableList.last(), uploadSize); @@ -6797,7 +6822,8 @@ void tst_QNetworkReply::authenticationCacheAfterCancel() // QTBUG-23136 workaround (needed even with danted v1.1.19): if (proxy.port() == 1081) { #ifdef QT_BUILD_INTERNAL - QNetworkAccessManagerPrivate::clearCache(&manager); + QNetworkAccessManagerPrivate::clearAuthenticationCache(&manager); + QNetworkAccessManagerPrivate::clearConnectionCache(&manager); #else return; #endif @@ -6908,17 +6934,17 @@ void tst_QNetworkReply::authenticationWithDifferentRealm() } #endif // !QT_NO_NETWORKPROXY -class QtBug13431Helper : public QObject { +class QtBug13431Helper : public QObject +{ Q_OBJECT public: QNetworkReply* m_reply; QTimer m_dlTimer; public slots: - void replyFinished(QNetworkReply*) { - QTestEventLoop::instance().exitLoop(); - } + void replyFinished(QNetworkReply*) { QTestEventLoop::instance().exitLoop(); } - void onReadAndReschedule() { + void onReadAndReschedule() + { const qint64 bytesReceived = m_reply->bytesAvailable(); if (bytesReceived && m_reply->readBufferSize()) { QByteArray data = m_reply->read(bytesReceived); @@ -7066,7 +7092,8 @@ void tst_QNetworkReply::qtbug22660gzipNoContentLengthEmptyContent() QCOMPARE(reply->readAll(), QByteArray()); } -class QtBug27161Helper : public QObject { +class QtBug27161Helper : public QObject +{ Q_OBJECT public: QtBug27161Helper(MiniHttpServer & server, const QByteArray & data): @@ -7076,16 +7103,19 @@ public: connect(&m_server, SIGNAL(newConnection()), this, SLOT(newConnectionSlot())); } public slots: - void newConnectionSlot(){ + void newConnectionSlot() + { connect(m_server.client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot())); } - void bytesWrittenSlot(){ + void bytesWrittenSlot() + { disconnect(m_server.client, SIGNAL(bytesWritten(qint64)), this, SLOT(bytesWrittenSlot())); m_Timer.singleShot(100, this, SLOT(timeoutSlot())); } - void timeoutSlot(){ + void timeoutSlot() + { m_server.doClose = true; // we need to emulate the bytesWrittenSlot call if the data is empty. if (m_data.size() == 0) @@ -7514,10 +7544,12 @@ void tst_QNetworkReply::httpUserAgent() void tst_QNetworkReply::synchronousAuthenticationCache() { - class MiniAuthServer : public MiniHttpServer { + class MiniAuthServer : public MiniHttpServer + { public: - MiniAuthServer(QThread *thread) : MiniHttpServer(QByteArray(), false, thread) {}; - virtual void reply() { + MiniAuthServer(QThread *thread) : MiniHttpServer(QByteArray(), false, thread) {} + virtual void reply() + { dataToTransmit = "HTTP/1.0 401 Unauthorized\r\n" @@ -7929,7 +7961,8 @@ public: qint64 bandwidthQuota; QTimer timer; - RateLimitedUploadDevice(QByteArray d) : QIODevice(),data(d),read(0),bandwidthQuota(0) { + RateLimitedUploadDevice(QByteArray d) : QIODevice(),data(d),read(0),bandwidthQuota(0) + { buffer.setData(data); buffer.open(QIODevice::ReadOnly); timer.setInterval(200); @@ -7937,12 +7970,14 @@ public: timer.start(); } - virtual qint64 writeData(const char* , qint64 ) { + virtual qint64 writeData(const char* , qint64 ) + { Q_ASSERT(false); return 0; } - virtual qint64 readData(char* data, qint64 maxlen) { + virtual qint64 readData(char* data, qint64 maxlen) + { //qDebug() << Q_FUNC_INFO << maxlen << bandwidthQuota; maxlen = qMin(maxlen, buffer.bytesAvailable()); maxlen = qMin(maxlen, bandwidthQuota); @@ -7959,24 +7994,17 @@ public: //qDebug() << Q_FUNC_INFO << maxlen << bandwidthQuota << read << ret << buffer.bytesAvailable(); return ret; } - virtual bool atEnd() const { - return buffer.atEnd(); - } - virtual qint64 size() const{ - return data.length(); - } + virtual bool atEnd() const { return buffer.atEnd(); } + virtual qint64 size() const { return data.length(); } qint64 bytesAvailable() const { return buffer.bytesAvailable() + QIODevice::bytesAvailable(); } - virtual bool isSequential() const{ // random access, we can seek - return false; - } - virtual bool seek ( qint64 pos ) { - return buffer.seek(pos); - } + virtual bool isSequential() const { return false; } // random access, we can seek + virtual bool seek (qint64 pos) { return buffer.seek(pos); } protected slots: - void timeoutSlot() { + void timeoutSlot() + { //qDebug() << Q_FUNC_INFO; bandwidthQuota = 8*1024; // fill quota emit readyRead(); @@ -8012,10 +8040,9 @@ void tst_QNetworkReply::putWithRateLimiting() void tst_QNetworkReply::ioHttpSingleRedirect() { QUrl localhost = QUrl("http://localhost"); - QByteArray http200Reply = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; // Setup server to which the second server will redirect to - MiniHttpServer server2(http200Reply); + MiniHttpServer server2(httpEmpty200Response); QUrl redirectUrl = QUrl(localhost); redirectUrl.setPort(server2.serverPort()); @@ -8057,11 +8084,9 @@ void tst_QNetworkReply::ioHttpChangeMaxRedirects() { QUrl localhost = QUrl("http://localhost"); - QByteArray http200Reply = "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n"; - MiniHttpServer server1(""); MiniHttpServer server2(""); - MiniHttpServer server3(http200Reply); + MiniHttpServer server3(httpEmpty200Response); QUrl server2Url(localhost); server2Url.setPort(server2.serverPort()); @@ -8145,6 +8170,221 @@ void tst_QNetworkReply::ioHttpRedirectErrors() QCOMPARE(spy.count(), 1); QCOMPARE(reply->error(), error); } + +struct SameOriginRedirector : MiniHttpServer +{ + SameOriginRedirector(const QByteArray &data, bool ssl = false) + : MiniHttpServer(data, ssl) + { } + + std::vector<QByteArray> responses; + + void reply() override + { + if (responses.empty()) { + dataToTransmit.clear(); + } else { + dataToTransmit = responses.back(); + responses.pop_back(); + } + + MiniHttpServer::reply(); + } +}; + +void tst_QNetworkReply::ioHttpRedirectPolicy_data() +{ + QTest::addColumn<QNetworkRequest::RedirectsPolicy>("policy"); + QTest::addColumn<bool>("ssl"); + QTest::addColumn<int>("redirectCount"); + QTest::addColumn<int>("statusCode"); + + QTest::newRow("manual-nossl") << QNetworkRequest::ManualRedirectsPolicy << false << 0 << 307; + QTest::newRow("manual-ssl") << QNetworkRequest::ManualRedirectsPolicy << true << 0 << 307; + QTest::newRow("nolesssafe-nossl") << QNetworkRequest::NoLessSafeRedirectsPolicy << false << 1 << 200; + QTest::newRow("nolesssafe-ssl") << QNetworkRequest::NoLessSafeRedirectsPolicy << true << 1 << 200; + QTest::newRow("same-origin-nossl") << QNetworkRequest::SameOriginRedirectsPolicy << false << 1 << 200; + QTest::newRow("same-origin-ssl") << QNetworkRequest::SameOriginRedirectsPolicy << true << 1 << 200; +} + +void tst_QNetworkReply::ioHttpRedirectPolicy() +{ + QFETCH(const QNetworkRequest::RedirectsPolicy, policy); + + QFETCH(const bool, ssl); +#ifdef QT_NO_SSL + if (ssl) + QSKIP("SSL is not supported"); +#endif + + QFETCH(const int, redirectCount); + QFETCH(const int, statusCode); + + // Setup HTTP server. + SameOriginRedirector redirectServer("", ssl); + + QUrl url(QLatin1String( +#ifndef QT_NO_SSL + ssl ? "https://localhost" : +#endif + "http://localhost")); + + url.setPort(redirectServer.serverPort()); + redirectServer.responses.push_back(httpEmpty200Response); + redirectServer.responses.push_back(tempRedirectReplyStr().arg(QString(url.toEncoded())).toLatin1()); + + // This is the default one we preserve between tests. + QCOMPARE(manager.redirectsPolicy(), QNetworkRequest::ManualRedirectsPolicy); + + manager.setRedirectsPolicy(policy); + QCOMPARE(manager.redirectsPolicy(), policy); + QNetworkReplyPtr reply(manager.get(QNetworkRequest(url))); + if (ssl) + reply->ignoreSslErrors(); + + // Restore default: + manager.setRedirectsPolicy(QNetworkRequest::ManualRedirectsPolicy); + QSignalSpy redirectSpy(reply.data(), SIGNAL(redirected(QUrl))); + QSignalSpy finishedSpy(reply.data(), SIGNAL(finished())); + QVERIFY2(waitForFinish(reply) == Success, msgWaitForFinished(reply)); + QCOMPARE(finishedSpy.count(), 1); + QCOMPARE(redirectSpy.count(), redirectCount); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); +} + +void tst_QNetworkReply::ioHttpRedirectPolicyErrors_data() +{ + QTest::addColumn<QNetworkRequest::RedirectsPolicy>("policy"); + QTest::addColumn<bool>("ssl"); + QTest::addColumn<QString>("location"); + QTest::addColumn<int>("maxRedirects"); + QTest::addColumn<QNetworkReply::NetworkError>("expectedError"); + + // 1. NoLessSafeRedirectsPolicy + QTest::newRow("nolesssafe-nossl-nossl-too-many") << QNetworkRequest::NoLessSafeRedirectsPolicy + << false << QString("http://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; + QTest::newRow("nolesssafe-ssl-ssl-too-many") << QNetworkRequest::NoLessSafeRedirectsPolicy + << true << QString("https:/localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; + QTest::newRow("nolesssafe-ssl-nossl-insecure-redirect") << QNetworkRequest::NoLessSafeRedirectsPolicy + << true << QString("http://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; + // 2. SameOriginRedirectsPolicy + QTest::newRow("same-origin-nossl-nossl-too-many") << QNetworkRequest::SameOriginRedirectsPolicy + << false << QString("http://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; + QTest::newRow("same-origin-ssl-ssl-too-many") << QNetworkRequest::SameOriginRedirectsPolicy + << true << QString("https://localhost:%1") << 0 << QNetworkReply::TooManyRedirectsError; + QTest::newRow("same-origin-https-http-wrong-protocol") << QNetworkRequest::SameOriginRedirectsPolicy + << true << QString("http://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; + QTest::newRow("same-origin-http-https-wrong-protocol") << QNetworkRequest::SameOriginRedirectsPolicy + << false << QString("https://localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; + QTest::newRow("same-origin-http-http-wrong-host") << QNetworkRequest::SameOriginRedirectsPolicy + << false << QString("http://not-so-localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; + QTest::newRow("same-origin-https-https-wrong-host") << QNetworkRequest::SameOriginRedirectsPolicy + << true << QString("https://not-so-localhost:%1") << 50 << QNetworkReply::InsecureRedirectError; + QTest::newRow("same-origin-http-http-wrong-port") << QNetworkRequest::SameOriginRedirectsPolicy + << false << QString("http://localhost/%1") << 50 << QNetworkReply::InsecureRedirectError; + QTest::newRow("same-origin-https-https-wrong-port") << QNetworkRequest::SameOriginRedirectsPolicy + << true << QString("https://localhost/%1") << 50 << QNetworkReply::InsecureRedirectError; +} + +void tst_QNetworkReply::ioHttpRedirectPolicyErrors() +{ + QFETCH(const QNetworkRequest::RedirectsPolicy, policy); + // This should never happen: + QVERIFY(policy != QNetworkRequest::ManualRedirectsPolicy); + + QFETCH(const bool, ssl); + QFETCH(const QString, location); + QFETCH(const int, maxRedirects); + QFETCH(const QNetworkReply::NetworkError, expectedError); + +#ifdef QT_NO_SSL + if (ssl || location.contains("https")) + QSKIP("SSL required to run this test"); +#endif + + // Setup the server. + MiniHttpServer server("", ssl); + server.setDataToTransmit(tempRedirectReplyStr().arg(location.arg(server.serverPort())).toLatin1()); + + QUrl url(QLatin1String( +#ifndef QT_NO_SSL + ssl ? "https://localhost" : +#endif + "http://localhost")); + url.setPort(server.serverPort()); + + QNetworkRequest request(url); + request.setMaximumRedirectsAllowed(maxRedirects); + // We always reset the policy to the default one ('Manual') after any related + // test is finished: + QCOMPARE(manager.redirectsPolicy(), QNetworkRequest::ManualRedirectsPolicy); + manager.setRedirectsPolicy(policy); + QCOMPARE(manager.redirectsPolicy(), policy); + + QNetworkReplyPtr reply(manager.get(request)); + // Set it back to default: + manager.setRedirectsPolicy(QNetworkRequest::ManualRedirectsPolicy); + + if (ssl) + reply->ignoreSslErrors(); + + QSignalSpy spy(reply.data(), SIGNAL(error(QNetworkReply::NetworkError))); + + QCOMPARE(waitForFinish(reply), int(Failure)); + QCOMPARE(spy.count(), 1); + QCOMPARE(reply->error(), expectedError); +} + +void tst_QNetworkReply::ioHttpUserVerifiedRedirect_data() +{ + QTest::addColumn<bool>("followRedirect"); + QTest::addColumn<int>("statusCode"); + + QTest::newRow("allow-redirect") << true << 200; + QTest::newRow("reject-redirect") << false << 307; +} + +void tst_QNetworkReply::ioHttpUserVerifiedRedirect() +{ + QFETCH(const bool, followRedirect); + QFETCH(const int, statusCode); + + // Setup HTTP server. + MiniHttpServer target(httpEmpty200Response, false); + QUrl url("http://localhost"); + url.setPort(target.serverPort()); + + MiniHttpServer redirectServer("", false); + redirectServer.setDataToTransmit(tempRedirectReplyStr().arg(QString(url.toEncoded())).toLatin1()); + url.setPort(redirectServer.serverPort()); + + QCOMPARE(manager.redirectsPolicy(), QNetworkRequest::ManualRedirectsPolicy); + manager.setRedirectsPolicy(QNetworkRequest::UserVerifiedRedirectsPolicy); + QCOMPARE(manager.redirectsPolicy(), QNetworkRequest::UserVerifiedRedirectsPolicy); + + QNetworkReplyPtr reply(manager.get(QNetworkRequest(url))); + reply->connect(reply.data(), &QNetworkReply::redirected, + [&](const QUrl &redirectUrl) { + qDebug() << "redirect to:" << redirectUrl; + if (followRedirect) { + qDebug() << "confirmed."; + emit reply->redirectAllowed(); + } else{ + qDebug() << "rejected."; + emit reply->abort(); + } + }); + + // Before any test failed, reset the policy to default: + manager.setRedirectsPolicy(QNetworkRequest::ManualRedirectsPolicy); + QCOMPARE(manager.redirectsPolicy(), QNetworkRequest::ManualRedirectsPolicy); + + QSignalSpy finishedSpy(reply.data(), SIGNAL(finished())); + waitForFinish(reply); + QCOMPARE(finishedSpy.count(), 1); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), statusCode); +} + #ifndef QT_NO_SSL class PutWithServerClosingConnectionImmediatelyHandler: public QObject @@ -8166,9 +8406,7 @@ signals: void corruptFileUploadReceived(); public slots: - void closeDelayed() { - m_socket->close(); - } + void closeDelayed() { m_socket->close(); } void readyReadSlot() { @@ -8193,17 +8431,18 @@ public slots: // We had received some data but it is corrupt! qDebug() << "CORRUPT" << m_receivedData.count(); - // Use this to track down the pattern of the corruption and conclude the source -// QFile a("/tmp/corrupt"); -// a.open(QIODevice::WriteOnly); -// a.write(m_receivedData); -// a.close(); +#if 0 // Use this to track down the pattern of the corruption and conclude the source + QFile a("/tmp/corrupt"); + a.open(QIODevice::WriteOnly); + a.write(m_receivedData); + a.close(); -// QFile b("/tmp/correct"); -// b.open(QIODevice::WriteOnly); -// b.write(m_expectedData); -// b.close(); + QFile b("/tmp/correct"); + b.open(QIODevice::WriteOnly); + b.write(m_expectedData); + b.close(); //exit(1); +#endif emit corruptFileUploadReceived(); } else { emit correctFileUploadReceived(); @@ -8220,26 +8459,26 @@ public: int m_repliesFinished; int m_expectedReplies; QByteArray m_expectedData; - PutWithServerClosingConnectionImmediatelyServer() : SslServer(), m_correctUploads(0), m_corruptUploads(0), m_repliesFinished(0), m_expectedReplies(0) + PutWithServerClosingConnectionImmediatelyServer() + : SslServer(), m_correctUploads(0), m_corruptUploads(0), + m_repliesFinished(0), m_expectedReplies(0) { QObject::connect(this, SIGNAL(newEncryptedConnection(QSslSocket*)), this, SLOT(createHandlerForConnection(QSslSocket*))); QObject::connect(this, SIGNAL(newPlainConnection(QSslSocket*)), this, SLOT(createHandlerForConnection(QSslSocket*))); } public slots: - void createHandlerForConnection(QSslSocket* s) { + void createHandlerForConnection(QSslSocket* s) + { PutWithServerClosingConnectionImmediatelyHandler *handler = new PutWithServerClosingConnectionImmediatelyHandler(s, m_expectedData); handler->setParent(this); QObject::connect(handler, SIGNAL(correctFileUploadReceived()), this, SLOT(increaseCorrect())); QObject::connect(handler, SIGNAL(corruptFileUploadReceived()), this, SLOT(increaseCorrupt())); } - void increaseCorrect() { - m_correctUploads++; - } - void increaseCorrupt() { - m_corruptUploads++; - } - void replyFinished() { + void increaseCorrect() { m_correctUploads++; } + void increaseCorrupt() { m_corruptUploads++; } + void replyFinished() + { m_repliesFinished++; if (m_repliesFinished == m_expectedReplies) { QTestEventLoop::instance().exitLoop(); diff --git a/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp b/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp index 82fa5cab9c..9c49e0c173 100644 --- a/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp +++ b/tests/auto/network/bearer/qnetworkconfiguration/tst_qnetworkconfiguration.cpp @@ -53,6 +53,7 @@ private slots: void comparison(); void children(); void isRoamingAvailable(); + void connectTimeout(); #endif }; @@ -181,6 +182,21 @@ void tst_QNetworkConfiguration::isRoamingAvailable() } } } + +void tst_QNetworkConfiguration::connectTimeout() +{ + QNetworkConfigurationManager manager; + QList<QNetworkConfiguration> configs = manager.allConfigurations(); + + foreach (QNetworkConfiguration networkConfiguration, configs) { + QCOMPARE(networkConfiguration.connectTimeout(), 30000); + + bool result = networkConfiguration.setConnectTimeout(100); + QVERIFY(result); + + QCOMPARE(networkConfiguration.connectTimeout(), 100); + } +} #endif QTEST_MAIN(tst_QNetworkConfiguration) diff --git a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp index a715c38f32..bc3f5650ba 100644 --- a/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp +++ b/tests/auto/network/kernel/qhostaddress/tst_qhostaddress.cpp @@ -274,6 +274,7 @@ void tst_QHostAddress::specialAddresses() QVERIFY(address == QHostAddress(address)); QVERIFY(!(QHostAddress(address) != QHostAddress(address))); QVERIFY(!(QHostAddress(address) != address)); + QVERIFY(!(address != QHostAddress(address))); { QHostAddress ha; diff --git a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp index f6d9b71aa2..41ed7d2b93 100644 --- a/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp +++ b/tests/auto/network/kernel/qhostinfo/tst_qhostinfo.cpp @@ -93,6 +93,10 @@ private slots: void lookupIPv4(); void lookupIPv6_data(); void lookupIPv6(); + void lookupConnectToFunctionPointer_data(); + void lookupConnectToFunctionPointer(); + void lookupConnectToLambda_data(); + void lookupConnectToLambda(); void reverseLookup_data(); void reverseLookup(); @@ -307,6 +311,74 @@ void tst_QHostInfo::lookupIPv6() QCOMPARE(tmp.join(' ').toLower(), expected.join(' ').toLower()); } +void tst_QHostInfo::lookupConnectToFunctionPointer_data() +{ + lookupIPv4_data(); +} + +void tst_QHostInfo::lookupConnectToFunctionPointer() +{ + QFETCH(QString, hostname); + QFETCH(int, err); + QFETCH(QString, addresses); + + lookupDone = false; + QHostInfo::lookupHost(hostname, this, &tst_QHostInfo::resultsReady); + + QTestEventLoop::instance().enterLoop(10); + QVERIFY(!QTestEventLoop::instance().timeout()); + QVERIFY(lookupDone); + + if (int(lookupResults.error()) != int(err)) + qWarning() << hostname << "=>" << lookupResults.errorString(); + QCOMPARE(int(lookupResults.error()), int(err)); + + QStringList tmp; + for (const auto &result : lookupResults.addresses()) + tmp.append(result.toString()); + tmp.sort(); + + QStringList expected = addresses.split(' '); + expected.sort(); + + QCOMPARE(tmp.join(' '), expected.join(' ')); +} + +void tst_QHostInfo::lookupConnectToLambda_data() +{ + lookupIPv4_data(); +} + +void tst_QHostInfo::lookupConnectToLambda() +{ + QFETCH(QString, hostname); + QFETCH(int, err); + QFETCH(QString, addresses); + + lookupDone = false; + QHostInfo::lookupHost(hostname, [=](const QHostInfo &hostInfo) { + resultsReady(hostInfo); + }); + + QTestEventLoop::instance().enterLoop(10); + QVERIFY(!QTestEventLoop::instance().timeout()); + QVERIFY(lookupDone); + + if (int(lookupResults.error()) != int(err)) + qWarning() << hostname << "=>" << lookupResults.errorString(); + QCOMPARE(int(lookupResults.error()), int(err)); + + QStringList tmp; + for (int i = 0; i < lookupResults.addresses().count(); ++i) + tmp.append(lookupResults.addresses().at(i).toString()); + tmp.sort(); + + QStringList expected = addresses.split(' '); + expected.sort(); + + QCOMPARE(tmp.join(' '), expected.join(' ')); +} + void tst_QHostInfo::reverseLookup_data() { QTest::addColumn<QString>("address"); diff --git a/tests/auto/network/kernel/qnetworkdatagram/qnetworkdatagram.pro b/tests/auto/network/kernel/qnetworkdatagram/qnetworkdatagram.pro index a2fe44060e..23d57f3fbf 100644 --- a/tests/auto/network/kernel/qnetworkdatagram/qnetworkdatagram.pro +++ b/tests/auto/network/kernel/qnetworkdatagram/qnetworkdatagram.pro @@ -1,5 +1,4 @@ CONFIG += testcase console -CONFIG -= app_bundle TARGET = tst_qnetworkdatagram SOURCES += tst_qnetworkdatagram.cpp QT = core network testlib diff --git a/tests/auto/opengl/qgl/tst_qgl.cpp b/tests/auto/opengl/qgl/tst_qgl.cpp index af0248b432..cf92c9fab6 100644 --- a/tests/auto/opengl/qgl/tst_qgl.cpp +++ b/tests/auto/opengl/qgl/tst_qgl.cpp @@ -1169,6 +1169,10 @@ void tst_QGL::currentFboSync() QGLWidget glw; glw.makeCurrent(); + // For some reason we offer inter-operatibility between QGL and QOpenGL + // paint engines. (?!) Let's check if the two engines can be used to perform + // drawing in turns on different targets within the same context. + { QGLFramebufferObject fbo1(256, 256, QGLFramebufferObject::CombinedDepthStencil); diff --git a/tests/auto/other/atwrapper/.gitignore b/tests/auto/other/atwrapper/.gitignore deleted file mode 100644 index 162ad53af6..0000000000 --- a/tests/auto/other/atwrapper/.gitignore +++ /dev/null @@ -1 +0,0 @@ -tst_atwrapper diff --git a/tests/auto/other/atwrapper/TODO b/tests/auto/other/atwrapper/TODO deleted file mode 100644 index 23a70c3c9e..0000000000 --- a/tests/auto/other/atwrapper/TODO +++ /dev/null @@ -1,17 +0,0 @@ -* Get rid of "Keep baseline" on test failure page (Lars) !! DONE !! -* Make to autotest (Simon) !! DONE !! -* Add visual diff (Everyone ;)) !! DONE !! -* Add flicker (Simon/Jesper) !! DONE !! -* Add third image -- base-baseline (Lars) !! DONE !! -* Add "view baselines" gallery, including the "base base line" (Lars) !! DONE !! -* Add PS printer driver engine test thingy (Eskil) !! DONE !! -* Add platform by platform comparison perl script. (Morton) -* Fix the QDateTime.fromString() weirdness on win32 in xmldata.cpp (Jesper) -* Have one result per page view (Lars) !! DONE !! -* Have "platform - hostname" on test overview (Lars) !! DONE !! -* Have the links on the overview page only show failures for that host.(All)!! DONE !! -* "onion skin" diff. (Jesper) -* Promote all to baseline -* Switch all to flicker/onion/whatever -* Add javascript confirmation for "make baseline" -* Make "single view" more stable diff --git a/tests/auto/other/atwrapper/atWrapper.cpp b/tests/auto/other/atwrapper/atWrapper.cpp deleted file mode 100644 index 8f623538f9..0000000000 --- a/tests/auto/other/atwrapper/atWrapper.cpp +++ /dev/null @@ -1,636 +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 <atWrapper.h> -#include <datagenerator/datagenerator.h> - -#include <QString> -#include <QHash> -#include <QFile> -#include <QFtp> -#include <QObject> -#include <QHostInfo> -#include <QWidget> -#include <QImage> -#include <QtTest/QSignalSpy> -#include <QLibraryInfo> - -static const char *ArthurDir = "../../arthur"; - -#include <string.h> - -atWrapper::atWrapper() -{ - - // initTests(); - -} - -bool atWrapper::initTests(bool *haveBaseline) -{ - qDebug() << "Running test on buildkey:" << QLibraryInfo::buildKey() << " qt version:" << qVersion(); - - qDebug( "Initializing tests..." ); - - if (!loadConfig( QHostInfo::localHostName().split( "." ).first() + ".ini" )) - return false; - - //Reset the FTP environment where the results are stored - *haveBaseline = setupFTP(); - - // Retrieve the latest test result baseline from the FTP server. - downloadBaseline(); - return true; -} - -void atWrapper::downloadBaseline() -{ - - qDebug() << "Now downloading baseline..."; - - QFtp ftp; - - QObject::connect( &ftp, SIGNAL(listInfo(QUrlInfo)), this, SLOT(ftpMgetAddToList(QUrlInfo)) ); - - //Making sure that the needed local directories exist. - - QHashIterator<QString, QString> j(enginesToTest); - - while ( j.hasNext() ) - { - j.next(); - - QDir dir( output ); - - if ( !dir.cd( j.key() + ".baseline" ) ) - dir.mkdir( j.key() + ".baseline" ); - - } - - //FTP to the host specified in the config file, and retrieve the test result baseline. - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - ftp.cd( ftpBaseDir ); - - QHashIterator<QString, QString> i(enginesToTest); - while ( i.hasNext() ) - { - i.next(); - mgetDirList.clear(); - mgetDirList << i.key() + ".baseline"; - ftp.cd( i.key() + ".baseline" ); - ftp.list(); - ftp.cd( ".." ); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - - ftpMgetDone( true ); - } - - ftp.close(); - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - -} - -void atWrapper::ftpMgetAddToList( const QUrlInfo &urlInfo ) -{ - //Simply adding to the list of files to download. - mgetDirList << urlInfo.name(); - -} - -void atWrapper::ftpMgetDone( bool error) -{ - Q_UNUSED( error ); - - //Downloading the files listed in mgetDirList... - QFtp ftp; - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - QFile* file; - - if ( mgetDirList.size() > 1 ) - for ( int i = 1; i < mgetDirList.size(); ++i ) - { - file = new QFile( QString( output ) + QLatin1Char('/') + mgetDirList.at( 0 ) - + QLatin1Char('/') + mgetDirList.at( i ) ); - if (file->open(QIODevice::WriteOnly)) { - ftp.get( ftpBaseDir + QLatin1Char('/') + mgetDirList.at( 0 ) + QLatin1Char('/') + mgetDirList.at( i ), file ); - ftp.list(); //Only there to fill up a slot in the pendingCommands queue. - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - file->close(); - } else { - qDebug() << "Couldn't open file for writing: " << file->fileName(); - } - } - - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); -} - -void atWrapper::uploadFailed( QString dir, QString filename, QByteArray filedata ) -{ - //Upload a failed test case image to the FTP server. - QFtp ftp; - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - ftp.cd( ftpBaseDir ); - ftp.cd( dir ); - - ftp.put( filedata, filename, QFtp::Binary ); - - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); -} - -// returns false if no baseline exists -bool atWrapper::setupFTP() -{ - qDebug( "Setting up FTP environment" ); - - QString dir = ""; - ftpMkDir( ftpBaseDir ); - - ftpBaseDir += QLatin1Char('/') + QLibraryInfo::buildKey(); - - ftpMkDir( ftpBaseDir ); - - ftpBaseDir += QLatin1Char('/') + QString( qVersion() ); - - ftpMkDir( ftpBaseDir ); - - QHashIterator<QString, QString> i(enginesToTest); - QHashIterator<QString, QString> j(enginesToTest); - - bool haveBaseline = true; - //Creating the baseline directories for each engine - while ( i.hasNext() ) - { - i.next(); - //qDebug() << "Creating dir with key:" << i.key(); - ftpMkDir( ftpBaseDir + QLatin1Char('/') + QString( i.key() ) + ".failed" ); - ftpMkDir( ftpBaseDir + QLatin1Char('/') + QString( i.key() ) + ".diff" ); - if (!ftpMkDir( ftpBaseDir + QLatin1Char('/') + QString( i.key() ) + ".baseline" )) - haveBaseline = false; - } - - - QFtp ftp; - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - ftp.cd( ftpBaseDir ); - //Deleting previous failed directory and all the files in it, then recreating it. - while ( j.hasNext() ) - { - j.next(); - rmDirList.clear(); - rmDirList << ftpBaseDir + QLatin1Char('/') + j.key() + ".failed/"; - ftpRmDir( j.key() + ".failed" ); - ftp.rmdir( j.key() + ".failed" ); - ftp.mkdir( j.key() + ".failed" ); - ftp.list(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - - rmDirList.clear(); - rmDirList << ftpBaseDir + QLatin1Char('/') + j.key() + ".diff/"; - ftpRmDir( j.key() + ".diff" ); - ftp.rmdir( j.key() + ".diff" ); - ftp.mkdir( j.key() + ".diff" ); - ftp.list(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - - } - - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - - return haveBaseline; -} - -void atWrapper::ftpRmDir( QString dir ) -{ - //Hack to remove a populated directory. (caveat: containing only files and empty dirs, not recursive!) - qDebug() << "Now removing directory: " << dir; - QFtp ftp; - QObject::connect( &ftp, SIGNAL(listInfo(QUrlInfo)), this, SLOT(ftpRmDirAddToList(QUrlInfo)) ); - QObject::connect( &ftp, SIGNAL(done(bool)), this, SLOT(ftpRmDirDone(bool)) ); - - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - ftp.list( ftpBaseDir + "/" + dir ); - ftp.close(); - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); -} - -void atWrapper::ftpRmDirDone( bool error ) -{ - //Deleting each file in the directory listning, rmDirList. - Q_UNUSED( error ); - - QFtp ftp; - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - - if ( rmDirList.size() > 1 ) - for (int i = 1; i < rmDirList.size(); ++i) - ftp.remove( rmDirList.at(0) + rmDirList.at( i ) ); - - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); -} - -// returns false if the directory already exists -bool atWrapper::ftpMkDir( QString dir ) -{ - //Simply used to avoid QFTP from bailing out and loosing a queue of commands. - // IE: conveniance. - QFtp ftp; - - QSignalSpy commandSpy(&ftp, SIGNAL(commandFinished(int,bool))); - - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - const int command = ftp.mkdir( dir ); - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); - - for (int i = 0; i < commandSpy.count(); ++i) - if (commandSpy.at(i).at(0) == command) - return commandSpy.at(i).at(1).toBool(); - - return false; -} - - -void atWrapper::ftpRmDirAddToList( const QUrlInfo &urlInfo ) -{ - //Just adding the file to the list for deletion - rmDirList << urlInfo.name(); -} - - -bool atWrapper::executeTests() -{ - qDebug("Executing the tests..."); - - QHashIterator<QString, QString> i(enginesToTest); - - DataGenerator generator; - - //Running datagenerator against all the frameworks specified in the config file. - while ( i.hasNext() ) - { - - i.next(); - - qDebug( "Now testing: " + i.key().toLatin1() ); - - char* params[13]; - //./bin/datagenerator -framework data/framework.ini -engine OpenGL -suite 1.1 -output outtest - - - QByteArray eng = i.key().toLatin1(); - QByteArray fwk = framework.toLatin1(); - QByteArray sut = suite.toLatin1(); - QByteArray out = output.toLatin1(); - QByteArray siz = size.toLatin1(); - QByteArray fill = fillColor.toLatin1(); - - params[1] = "-framework"; - params[2] = fwk.data(); - params[3] = "-engine"; - params[4] = eng.data(); - params[5] = "-suite"; - params[6] = sut.data(); - params[7] = "-output"; - params[8] = out.data(); - params[9] = "-size"; - params[10] = siz.data(); - params[11] = "-fill"; - params[12] = fill.data(); - - generator.run( 13, params ); - } - - return true; -} - -void atWrapper::createBaseline() -{ - qDebug( "Now uploading a baseline of only the latest test values" ); - - QHashIterator<QString, QString> i(enginesToTest); - - QDir dir( output ); - QFtp ftp; - ftp.connectToHost( ftpHost ); - ftp.login( ftpUser, ftpPass ); - ftp.cd( ftpBaseDir ); - //Upload all the latest test results to the FTP server's baseline directory. - while ( i.hasNext() ) - { - - i.next(); - dir.cd( i.key() ); - ftp.cd( i.key() + ".baseline" ); - dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); - dir.setNameFilters( QStringList() << "*.png" ); - QFileInfoList list = dir.entryInfoList(); - dir.cd( ".." ); - for (int n = 0; n < list.size(); n++) - { - QFileInfo fileInfo = list.at( n ); - QFile file( QString( output ) + QLatin1Char('/') + i.key() + QLatin1Char('/') + fileInfo.fileName() ); - file.open( QIODevice::ReadOnly ); - QByteArray fileData = file.readAll(); - //qDebug() << "Sending up:" << fileInfo.fileName() << "with file size" << fileData.size(); - file.close(); - ftp.put( fileData, fileInfo.fileName(), QFtp::Binary ); - } - - ftp.cd( ".." ); - } - - ftp.close(); - - while ( ftp.hasPendingCommands() ) - QCoreApplication::instance()->processEvents(); -} - -bool atWrapper::compare() -{ - qDebug( "Now comparing the results to the baseline" ); - - QHashIterator<QString, QString> i(enginesToTest); - - while ( i.hasNext() ) - { - i.next(); - - compareDirs( output , i.key() ); - - } - - return true; -} - -void atWrapper::compareDirs( QString basedir, QString target ) -{ - - QDir dir( basedir ); - - /* The following should be redundant now. - - if ( !dir.cd( target + ".failed" ) ) - dir.mkdir( target + ".failed" ); - else - dir.cdUp(); - - */ - - if ( !dir.cd( target + ".diff" ) ) - dir.mkdir( target + ".diff" ); - else - dir.cdUp(); - - - - //Perform comparisons between the two directories. - - dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks); - dir.setNameFilters( QStringList() << "*.png" ); - dir.cd( target + ".baseline" ); - QFileInfoList list = dir.entryInfoList(); - - for (int i = 0; i < list.size(); ++i) - { - QFileInfo fileInfo = list.at(i); - diff ( basedir, target, fileInfo.fileName() ); - } -} - -bool atWrapper::diff( QString basedir, QString dir, QString target ) -{ - //Comparing the two specified files, and then uploading them to - //the ftp server if they differ - - basedir += QLatin1Char('/') + dir; - QString one = basedir + ".baseline/" + target; - QString two = basedir + QLatin1Char('/') + target; - - QFile file( one ); - - file.open( QIODevice::ReadOnly ); - QByteArray contentsOfOne = file.readAll(); - file.close(); - - file.setFileName( two ); - - file.open( QIODevice::ReadOnly ); - QByteArray contentsOfTwo = file.readAll(); - file.close(); - - if ( contentsOfTwo.size() == 0 ) - { - qDebug() << "No test result found for baseline: " << one; - file.setFileName( one ); - file.open( QIODevice::ReadOnly ); - file.copy( basedir + ".failed/" + target + "_missing" ); - uploadFailed( dir + ".failed", target + "_missing", contentsOfTwo ); - return false; - } - - - if ( ( memcmp( contentsOfOne, contentsOfTwo, contentsOfOne.size() ) ) == 0 ) - return true; - else - { - qDebug() << "Sorry, the result did not match: " << one; - file.setFileName( two ); - file.open( QIODevice::ReadOnly ); - file.copy( basedir + ".failed/" + target ); - file.close(); - uploadFailed( dir + ".failed", target, contentsOfTwo ); - uploadDiff( basedir, dir, target ); - return false; - } -} - -void atWrapper::uploadDiff( QString basedir, QString dir, QString filename ) -{ - - qDebug() << basedir; - QImage im1( basedir + ".baseline/" + filename ); - QImage im2( basedir + QLatin1Char('/') + filename ); - - QImage im3(im1.size(), QImage::Format_ARGB32); - - im1 = im1.convertToFormat(QImage::Format_ARGB32); - im2 = im2.convertToFormat(QImage::Format_ARGB32); - - for ( int y=0; y<im1.height(); ++y ) - { - uint *s = (uint *) im1.scanLine(y); - uint *d = (uint *) im2.scanLine(y); - uint *w = (uint *) im3.scanLine(y); - - for ( int x=0; x<im1.width(); ++x ) - { - if (*s != *d) - *w = 0xff000000; - else - *w = 0xffffffff; - w++; - s++; - d++; - } - } - - im3.save( basedir + ".diff/" + filename ,"PNG"); - - QFile file( basedir + ".diff/" + filename ); - file.open( QIODevice::ReadOnly ); - QByteArray contents = file.readAll(); - file.close(); - - uploadFailed( dir + ".diff", filename, contents ); - -} - -bool atWrapper::loadConfig( QString path ) -{ - qDebug() << "Loading config file from ... " << path; - configPath = path; - //If there is no config file, don't proceed; - if ( !QFile::exists( path ) ) - { - return false; - } - - - QSettings settings( path, QSettings::IniFormat, this ); - - - //FIXME: Switch to QStringList or something, hash is not needed! - int numEngines = settings.beginReadArray("engines"); - - for ( int i = 0; i < numEngines; ++i ) - { - settings.setArrayIndex(i); - enginesToTest.insert( settings.value( "engine" ).toString(), "Info here please :p" ); - } - - settings.endArray(); - - framework = QString(ArthurDir) + QDir::separator() + settings.value( "framework" ).toString(); - suite = settings.value( "suite" ).toString(); - output = settings.value( "output" ).toString(); - size = settings.value( "size", "480,360" ).toString(); - fillColor = settings.value( "fill", "white" ).toString(); - ftpUser = settings.value( "ftpUser" ).toString(); - ftpPass = settings.value( "ftpPass" ).toString(); - ftpHost = settings.value( "ftpHost" ).toString(); - ftpBaseDir = settings.value( "ftpBaseDir" ).toString(); - - - QDir::current().mkdir( output ); - - output += QLatin1Char('/') + QLibraryInfo::buildKey(); - - QDir::current().mkdir( output ); - - output += QLatin1Char('/') + QString( qVersion() ); - - QDir::current().mkdir( output ); - - - ftpBaseDir += QLatin1Char('/') + QHostInfo::localHostName().split( QLatin1Char('.') ).first(); - - -/* - framework = "data/framework.ini"; - suite = "1.1"; - output = "testresults"; - ftpUser = "anonymous"; - ftpPass = "anonymouspass"; - ftpHost = "kramer.troll.no"; - ftpBaseDir = "/arthurtest"; -*/ - return true; -} - -bool atWrapper::runAutoTests() -{ - //SVG needs this widget... - QWidget dummy; - - bool haveBaseline = false; - - if (!initTests(&haveBaseline)) - return false; - executeTests(); - - if ( !haveBaseline ) - { - qDebug( " First run! Creating baseline..." ); - createBaseline(); - } - else - { - qDebug( " Comparing results..." ); - compare(); - } - return true; -} diff --git a/tests/auto/other/atwrapper/atWrapper.h b/tests/auto/other/atwrapper/atWrapper.h deleted file mode 100644 index dab2b579e3..0000000000 --- a/tests/auto/other/atwrapper/atWrapper.h +++ /dev/null @@ -1,80 +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$ -** -****************************************************************************/ -#ifndef ATWRAPPER_H -#define ATWRAPPER_H - -#include <QHash> -#include <QString> -#include <QUrlInfo> -#include <QColor> - -class atWrapper : public QObject -{ - Q_OBJECT - - public: - atWrapper(); - bool runAutoTests(); - - private: - bool executeTests(); - bool initTests(bool *haveBaseline); - bool compare(); - void createBaseline(); - bool loadConfig( QString ); - void compareDirs( QString, QString ); - bool diff( QString, QString, QString ); - void downloadBaseline(); - void uploadFailed( QString, QString, QByteArray ); - bool ftpMkDir( QString ); - void ftpRmDir( QString ); - bool setupFTP(); - void uploadDiff( QString, QString, QString ); - - QHash<QString, QString> enginesToTest; - QString framework; - QString suite; - QString output; - QString size; - QString ftpUser; - QString ftpPass; - QString ftpHost; - QString ftpBaseDir; - QList<QString> rmDirList; - QList<QString> mgetDirList; - QString configPath; - QString fillColor; - - private slots: - void ftpRmDirAddToList( const QUrlInfo &urlInfo ); - void ftpRmDirDone( bool ); - void ftpMgetAddToList( const QUrlInfo &urlInfo ); - void ftpMgetDone( bool ); -}; - -#endif diff --git a/tests/auto/other/atwrapper/atWrapper.pro b/tests/auto/other/atwrapper/atWrapper.pro deleted file mode 100644 index 1617ae89d1..0000000000 --- a/tests/auto/other/atwrapper/atWrapper.pro +++ /dev/null @@ -1,21 +0,0 @@ -ARTHUR=$$QT_SOURCE_TREE/tests/arthur -COMMON_FOLDER = $$ARTHUR/common -include($$ARTHUR/arthurtester.pri) -INCLUDEPATH += $$ARTHUR -DEFINES += SRCDIR=\\\"$$PWD\\\" - -QT += xml svg network testlib - -qtHaveModule(opengl): QT += opengl - -include($$ARTHUR/datagenerator/datagenerator.pri) - -CONFIG += testcase - -HEADERS += atWrapper.h -SOURCES += atWrapperAutotest.cpp atWrapper.cpp - -TARGET = tst_atwrapper - -#include($$COMMON_FOLDER/common.pri) -DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 diff --git a/tests/auto/other/atwrapper/desert.ini b/tests/auto/other/atwrapper/desert.ini deleted file mode 100644 index 6d8605252d..0000000000 --- a/tests/auto/other/atwrapper/desert.ini +++ /dev/null @@ -1,14 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=NativeXRender -2\engine=PDF -3\engine=Raster -size=3 diff --git a/tests/auto/other/atwrapper/ephron.ini b/tests/auto/other/atwrapper/ephron.ini deleted file mode 100644 index eeccb3b6ef..0000000000 --- a/tests/auto/other/atwrapper/ephron.ini +++ /dev/null @@ -1,14 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=oxygen -size=256 -fill=transparent - -[engines] -1\engine=Raster -size=1 diff --git a/tests/auto/other/atwrapper/gullgubben.ini b/tests/auto/other/atwrapper/gullgubben.ini deleted file mode 100644 index 3a664dddd5..0000000000 --- a/tests/auto/other/atwrapper/gullgubben.ini +++ /dev/null @@ -1,12 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=OpenGL -size=1 diff --git a/tests/auto/other/atwrapper/honshu.ini b/tests/auto/other/atwrapper/honshu.ini deleted file mode 100644 index 3b7751a128..0000000000 --- a/tests/auto/other/atwrapper/honshu.ini +++ /dev/null @@ -1,16 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=NativeWin32 -2\engine=PDF -3\engine=Raster -4\engine=OpenGL -5\engine=WinPrint -size=5 diff --git a/tests/auto/other/atwrapper/kramer.ini b/tests/auto/other/atwrapper/kramer.ini deleted file mode 100644 index 289d8a8b7e..0000000000 --- a/tests/auto/other/atwrapper/kramer.ini +++ /dev/null @@ -1,12 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=Raster -size=1 diff --git a/tests/auto/other/atwrapper/scruffy.ini b/tests/auto/other/atwrapper/scruffy.ini deleted file mode 100644 index 329f537e6f..0000000000 --- a/tests/auto/other/atwrapper/scruffy.ini +++ /dev/null @@ -1,15 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.nokia.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=NativeMac -2\engine=PDF -3\engine=Raster -4\engine=OpenGL -size=4 diff --git a/tests/auto/other/atwrapper/spareribs.ini b/tests/auto/other/atwrapper/spareribs.ini deleted file mode 100644 index 78ff9e985f..0000000000 --- a/tests/auto/other/atwrapper/spareribs.ini +++ /dev/null @@ -1,14 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=NativeWin32 -2\engine=PDF -3\engine=Raster -size=3 diff --git a/tests/auto/other/atwrapper/titan.ini b/tests/auto/other/atwrapper/titan.ini deleted file mode 100644 index 3a0b0dfd31..0000000000 --- a/tests/auto/other/atwrapper/titan.ini +++ /dev/null @@ -1,13 +0,0 @@ -[General] -framework=data/framework.ini -ftpBaseDir=/arthurtest -ftpHost=kramer.troll.no -ftpPass=anonymouspass -ftpUser=anonymous -output=testresults -suite=1.1 - -[engines] -1\engine=NativeXRender -2\engine=OpenGL -size=2 diff --git a/tests/auto/other/lancelot/lancelot.pro b/tests/auto/other/lancelot/lancelot.pro index b492611ca7..73c12e67a2 100644 --- a/tests/auto/other/lancelot/lancelot.pro +++ b/tests/auto/other/lancelot/lancelot.pro @@ -1,5 +1,4 @@ CONFIG += testcase -CONFIG -= app_bundle TARGET = tst_lancelot QT += testlib diff --git a/tests/auto/other/lancelot/paintcommands.cpp b/tests/auto/other/lancelot/paintcommands.cpp index 2e6cb09aa5..971b9b5fe7 100644 --- a/tests/auto/other/lancelot/paintcommands.cpp +++ b/tests/auto/other/lancelot/paintcommands.cpp @@ -2378,6 +2378,8 @@ void PaintCommands::command_surface_begin(QRegExp re) #ifndef QT_NO_OPENGL m_default_glcontext = QOpenGLContext::currentContext(); m_surface_glcontext = new QOpenGLContext(); + // Pick up the format from the current context; this is especially + // important in order to pick the right version/profile to test. m_surface_glcontext->setFormat(m_default_glcontext->format()); m_surface_glcontext->create(); m_surface_glcontext->makeCurrent(m_default_glcontext->surface()); diff --git a/tests/auto/other/lancelot/tst_lancelot.cpp b/tests/auto/other/lancelot/tst_lancelot.cpp index 8fc0521102..63c62bab86 100644 --- a/tests/auto/other/lancelot/tst_lancelot.cpp +++ b/tests/auto/other/lancelot/tst_lancelot.cpp @@ -53,7 +53,7 @@ private: }; void setupTestSuite(const QStringList& blacklist = QStringList()); - void runTestSuite(GraphicsEngine engine, QImage::Format format); + void runTestSuite(GraphicsEngine engine, QImage::Format format, const QSurfaceFormat &contextFormat = QSurfaceFormat()); void paint(QPaintDevice *device, GraphicsEngine engine, const QStringList &script, const QString &filePath); QStringList qpsFiles; @@ -69,6 +69,8 @@ private slots: void testRasterARGB32PM(); void testRasterRGB32_data(); void testRasterRGB32(); + void testRasterARGB32_data(); + void testRasterARGB32(); void testRasterRGB16_data(); void testRasterRGB16(); void testRasterA2RGB30PM_data(); @@ -83,8 +85,11 @@ private slots: #ifndef QT_NO_OPENGL void testOpenGL_data(); void testOpenGL(); + void testCoreOpenGL_data(); + void testCoreOpenGL(); private: bool checkSystemGLSupport(); + bool checkSystemCoreGLSupport(); #endif }; @@ -134,6 +139,17 @@ void tst_Lancelot::testRasterARGB32PM() } +void tst_Lancelot::testRasterARGB32_data() +{ + setupTestSuite(); +} + +void tst_Lancelot::testRasterARGB32() +{ + runTestSuite(Raster, QImage::Format_ARGB32); +} + + void tst_Lancelot::testRasterRGB32_data() { setupTestSuite(); @@ -223,6 +239,32 @@ bool tst_Lancelot::checkSystemGLSupport() return true; } +bool tst_Lancelot::checkSystemCoreGLSupport() +{ + if (QOpenGLContext::openGLModuleType() != QOpenGLContext::LibGL) + return false; + + QSurfaceFormat coreFormat; + coreFormat.setVersion(3, 2); + coreFormat.setProfile(QSurfaceFormat::CoreProfile); + QWindow win; + win.setSurfaceType(QSurface::OpenGLSurface); + win.setFormat(coreFormat); + win.create(); + QOpenGLFramebufferObjectFormat fmt; + fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); + fmt.setSamples(4); + QOpenGLContext ctx; + ctx.setFormat(coreFormat); + if (!ctx.create() || !ctx.makeCurrent(&win)) + return false; + QOpenGLFramebufferObject fbo(800, 800, fmt); + if (!fbo.isValid() || !fbo.bind()) + return false; + + return true; +} + void tst_Lancelot::testOpenGL_data() { if (!checkSystemGLSupport()) @@ -236,6 +278,22 @@ void tst_Lancelot::testOpenGL() { runTestSuite(OpenGL, QImage::Format_RGB32); } + +void tst_Lancelot::testCoreOpenGL_data() +{ + if (!checkSystemCoreGLSupport()) + QSKIP("System under test does not meet preconditions for Core Profile GL testing. Skipping."); + QStringList localBlacklist = QStringList() << QLatin1String("rasterops.qps"); + setupTestSuite(localBlacklist); +} + +void tst_Lancelot::testCoreOpenGL() +{ + QSurfaceFormat coreFormat; + coreFormat.setVersion(3, 2); + coreFormat.setProfile(QSurfaceFormat::CoreProfile); + runTestSuite(OpenGL, QImage::Format_RGB32, coreFormat); +} #endif @@ -250,7 +308,7 @@ void tst_Lancelot::setupTestSuite(const QStringList& blacklist) } -void tst_Lancelot::runTestSuite(GraphicsEngine engine, QImage::Format format) +void tst_Lancelot::runTestSuite(GraphicsEngine engine, QImage::Format format, const QSurfaceFormat &contextFormat) { QFETCH(QString, qpsFile); @@ -266,11 +324,13 @@ void tst_Lancelot::runTestSuite(GraphicsEngine engine, QImage::Format format) } else if (engine == OpenGL) { QWindow win; win.setSurfaceType(QSurface::OpenGLSurface); + win.setFormat(contextFormat); win.create(); QOpenGLFramebufferObjectFormat fmt; fmt.setAttachment(QOpenGLFramebufferObject::CombinedDepthStencil); fmt.setSamples(4); QOpenGLContext ctx; + ctx.setFormat(contextFormat); QVERIFY(ctx.create()); QVERIFY(ctx.makeCurrent(&win)); QOpenGLFramebufferObject fbo(800, 800, fmt); @@ -291,7 +351,7 @@ void tst_Lancelot::paint(QPaintDevice *device, GraphicsEngine engine, const QStr //pcmd.setShouldDrawText(false); switch (engine) { case OpenGL: - pcmd.setType(OpenGLBufferType); + pcmd.setType(OpenGLBufferType); // version/profile is communicated through the context's format() break; case Raster: // fallthrough default: diff --git a/tests/auto/other/macplist/tst_macplist.cpp b/tests/auto/other/macplist/tst_macplist.cpp index 0f07095b67..755cc462f5 100644 --- a/tests/auto/other/macplist/tst_macplist.cpp +++ b/tests/auto/other/macplist/tst_macplist.cpp @@ -155,9 +155,12 @@ void tst_MacPlist::test_plist() QString infoPlist = QLatin1String("Info.plist"); QDir dir(QCoreApplication::applicationDirPath()); +#ifndef Q_OS_MACOS + // macOS builds tests as single executables, iOS/tvOS/watchOS does not QVERIFY(dir.cdUp()); QVERIFY(dir.cdUp()); QVERIFY(dir.cdUp()); +#endif QVERIFY(dir.cd(QLatin1String("app"))); QVERIFY(dir.cd(QLatin1String("app.app"))); QVERIFY(dir.cd(QLatin1String("Contents"))); diff --git a/tests/auto/other/modeltest/modeltest.cpp b/tests/auto/other/modeltest/modeltest.cpp index c1784c2edc..4da00bda4d 100644 --- a/tests/auto/other/modeltest/modeltest.cpp +++ b/tests/auto/other/modeltest/modeltest.cpp @@ -104,10 +104,10 @@ void ModelTest::runAllTests() */ void ModelTest::nonDestructiveBasicTest() { - QVERIFY( model->buddy ( QModelIndex() ) == QModelIndex() ); + QVERIFY(!model->buddy(QModelIndex()).isValid()); model->canFetchMore ( QModelIndex() ); QVERIFY( model->columnCount ( QModelIndex() ) >= 0 ); - QVERIFY( model->data ( QModelIndex() ) == QVariant() ); + QCOMPARE(model->data(QModelIndex()), QVariant()); fetchingMore = true; model->fetchMore ( QModelIndex() ); fetchingMore = false; @@ -121,7 +121,7 @@ void ModelTest::nonDestructiveBasicTest() QVariant cache; model->match ( QModelIndex(), -1, cache ); model->mimeTypes(); - QVERIFY( model->parent ( QModelIndex() ) == QModelIndex() ); + QVERIFY(!model->parent(QModelIndex()).isValid()); QVERIFY( model->rowCount() >= 0 ); QVariant variant; model->setData ( QModelIndex(), variant, -1 ); @@ -211,9 +211,9 @@ void ModelTest::index() { // qDebug() << "i"; // Make sure that invalid values returns an invalid index - QVERIFY( model->index ( -2, -2 ) == QModelIndex() ); - QVERIFY( model->index ( -2, 0 ) == QModelIndex() ); - QVERIFY( model->index ( 0, -2 ) == QModelIndex() ); + QVERIFY(!model->index(-2, -2).isValid()); + QVERIFY(!model->index(-2, 0).isValid()); + QVERIFY(!model->index(0, -2).isValid()); int rows = model->rowCount(); int columns = model->columnCount(); @@ -222,13 +222,13 @@ void ModelTest::index() return; // Catch off by one errors - QVERIFY( model->index ( rows, columns ) == QModelIndex() ); - QVERIFY( model->index ( 0, 0 ).isValid() ); + QVERIFY(!model->index(rows, columns).isValid()); + QVERIFY(model->index(0, 0).isValid()); // Make sure that the same index is *always* returned QModelIndex a = model->index ( 0, 0 ); QModelIndex b = model->index ( 0, 0 ); - QVERIFY( a == b ); + QCOMPARE(a, b); // index() is tested more extensively in checkChildren(), // but this catches the big mistakes @@ -242,7 +242,7 @@ void ModelTest::parent() // qDebug() << "p"; // Make sure the model won't crash and will return an invalid QModelIndex // when asked for the parent of an invalid index. - QVERIFY( model->parent ( QModelIndex() ) == QModelIndex() ); + QVERIFY(!model->parent(QModelIndex()).isValid()); if ( model->rowCount() == 0 ) return; @@ -255,13 +255,13 @@ void ModelTest::parent() // Common error test #1, make sure that a top level index has a parent // that is a invalid QModelIndex. QModelIndex topIndex = model->index ( 0, 0, QModelIndex() ); - QVERIFY( model->parent ( topIndex ) == QModelIndex() ); + QVERIFY(!model->parent(topIndex).isValid()); // Common error test #2, make sure that a second level index has a parent // that is the first level index. if ( model->rowCount ( topIndex ) > 0 ) { QModelIndex childIndex = model->index ( 0, 0, topIndex ); - QVERIFY( model->parent ( childIndex ) == topIndex ); + QCOMPARE(model->parent(childIndex), topIndex); } // Common error test #3, the second column should NOT have the same children @@ -336,28 +336,28 @@ void ModelTest::checkChildren ( const QModelIndex &parent, int currentDepth ) QVERIFY( model->hasIndex ( r, c, parent ) ); QModelIndex index = model->index ( r, c, parent ); // rowCount() and columnCount() said that it existed... - QVERIFY( index.isValid() ); + QVERIFY(index.isValid()); // index() should always return the same index when called twice in a row QModelIndex modifiedIndex = model->index ( r, c, parent ); - QVERIFY( index == modifiedIndex ); + QCOMPARE(index, modifiedIndex); // Make sure we get the same index if we request it twice in a row QModelIndex a = model->index ( r, c, parent ); QModelIndex b = model->index ( r, c, parent ); - QVERIFY( a == b ); + QCOMPARE(a, b); { const QModelIndex sibling = model->sibling( r, c, topLeftChild ); - QVERIFY( index == sibling ); + QCOMPARE(index, sibling); } { const QModelIndex sibling = topLeftChild.sibling( r, c ); - QVERIFY( index == sibling ); + QCOMPARE(index, sibling); } // Some basic checking on the index that is returned - QVERIFY( index.model() == model ); + QCOMPARE(index.model(), model); QCOMPARE( index.row(), r ); QCOMPARE( index.column(), c ); // While you can technically return a QVariant usually this is a sign @@ -387,7 +387,7 @@ void ModelTest::checkChildren ( const QModelIndex &parent, int currentDepth ) // make sure that after testing the children that the index doesn't change. QModelIndex newerIndex = model->index ( r, c, parent ); - QVERIFY( index == newerIndex ); + QCOMPARE(index, newerIndex); } } } @@ -438,7 +438,7 @@ void ModelTest::data() // Check that the alignment is one we know about QVariant textAlignmentVariant = model->data ( model->index ( 0, 0 ), Qt::TextAlignmentRole ); if ( textAlignmentVariant.isValid() ) { - int alignment = textAlignmentVariant.toInt(); + Qt::Alignment alignment = textAlignmentVariant.value<Qt::Alignment>(); QCOMPARE( alignment, ( alignment & ( Qt::AlignHorizontal_Mask | Qt::AlignVertical_Mask ) ) ); } @@ -490,7 +490,7 @@ void ModelTest::rowsAboutToBeInserted ( const QModelIndex &parent, int start, in void ModelTest::rowsInserted ( const QModelIndex & parent, int start, int end ) { Changing c = insert.pop(); - QVERIFY( c.parent == parent ); + QCOMPARE(c.parent, parent); // qDebug() << "rowsInserted" << "start=" << start << "end=" << end << "oldsize=" << c.oldSize // << "parent=" << model->data ( parent ).toString() << "current rowcount of parent=" << model->rowCount ( parent ); @@ -500,8 +500,8 @@ void ModelTest::rowsInserted ( const QModelIndex & parent, int start, int end ) // } // qDebug(); - QVERIFY( c.oldSize + ( end - start + 1 ) == model->rowCount ( parent ) ); - QVERIFY( c.last == model->data ( model->index ( start - 1, 0, c.parent ) ) ); + QCOMPARE(c.oldSize + (end - start + 1), model->rowCount(parent)); + QCOMPARE(c.last, model->data(model->index(start - 1, 0, c.parent))); if (c.next != model->data(model->index(end + 1, 0, c.parent))) { qDebug() << start << end; @@ -510,7 +510,7 @@ void ModelTest::rowsInserted ( const QModelIndex & parent, int start, int end ) qDebug() << c.next << model->data(model->index(end + 1, 0, c.parent)); } - QVERIFY( c.next == model->data ( model->index ( end + 1, 0, c.parent ) ) ); + QCOMPARE(c.next, model->data(model->index(end + 1, 0, c.parent))); } void ModelTest::layoutAboutToBeChanged() @@ -523,7 +523,7 @@ void ModelTest::layoutChanged() { for ( int i = 0; i < changing.count(); ++i ) { QPersistentModelIndex p = changing[i]; - QVERIFY( p == model->index ( p.row(), p.column(), p.parent() ) ); + QCOMPARE(QModelIndex(p), model->index(p.row(), p.column(), p.parent())); } changing.clear(); } @@ -553,10 +553,10 @@ void ModelTest::rowsRemoved ( const QModelIndex & parent, int start, int end ) { qDebug() << "rr" << parent << start << end; Changing c = remove.pop(); - QVERIFY( c.parent == parent ); - QVERIFY( c.oldSize - ( end - start + 1 ) == model->rowCount ( parent ) ); - QVERIFY( c.last == model->data ( model->index ( start - 1, 0, c.parent ) ) ); - QVERIFY( c.next == model->data ( model->index ( start, 0, c.parent ) ) ); + QCOMPARE(c.parent, parent); + QCOMPARE(c.oldSize - (end - start + 1), model->rowCount(parent)); + QCOMPARE(c.last, model->data(model->index(start - 1, 0, c.parent))); + QCOMPARE(c.next, model->data(model->index(start, 0, c.parent))); } void ModelTest::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) diff --git a/tests/auto/other/other.pro b/tests/auto/other/other.pro index 0babac4b6f..a12f08488d 100644 --- a/tests/auto/other/other.pro +++ b/tests/auto/other/other.pro @@ -2,7 +2,6 @@ TEMPLATE=subdirs QT_FOR_CONFIG += gui-private SUBDIRS=\ - # atwrapper \ # QTBUG-19452 compiler \ gestures \ lancelot \ diff --git a/tests/auto/other/qaccessibility/qaccessibility.pro b/tests/auto/other/qaccessibility/qaccessibility.pro index fb9de6f450..727d5fe0d7 100644 --- a/tests/auto/other/qaccessibility/qaccessibility.pro +++ b/tests/auto/other/qaccessibility/qaccessibility.pro @@ -12,6 +12,5 @@ win32 { include(../../../../src/3rdparty/iaccessible2/iaccessible2.pri) DEFINES += QT_SUPPORTS_IACCESSIBLE2 } - LIBS += -luuid - !winphone: LIBS += -loleacc -loleaut32 -lole32 + LIBS += -luuid -loleacc -loleaut32 -lole32 } diff --git a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp index 11baee7335..4f60fe3d96 100644 --- a/tests/auto/other/qaccessibility/tst_qaccessibility.cpp +++ b/tests/auto/other/qaccessibility/tst_qaccessibility.cpp @@ -3001,11 +3001,11 @@ void tst_QAccessibility::treeTest() QVERIFY(table2); QCOMPARE(table2->columnCount(), 2); QCOMPARE(table2->rowCount(), 2); - QAccessibleInterface *cell1; - QVERIFY(cell1 = table2->cellAt(0,0)); + QAccessibleInterface *cell1 = table2->cellAt(0,0); + QVERIFY(cell1); QCOMPARE(cell1->text(QAccessible::Name), QString("Spain")); - QAccessibleInterface *cell2; - QVERIFY(cell2 = table2->cellAt(1,0)); + QAccessibleInterface *cell2 = table2->cellAt(1,0); + QVERIFY(cell2); QCOMPARE(cell2->text(QAccessible::Name), QString("Austria")); QCOMPARE(cell2->role(), QAccessible::TreeItem); QCOMPARE(cell2->tableCellInterface()->rowIndex(), 1); @@ -3129,8 +3129,8 @@ void tst_QAccessibility::tableTest() QVERIFY(table2); QCOMPARE(table2->columnCount(), 3); QCOMPARE(table2->rowCount(), 3); - QAccessibleInterface *cell1; - QVERIFY(cell1 = table2->cellAt(0,0)); + QAccessibleInterface *cell1 = table2->cellAt(0,0); + QVERIFY(cell1); QCOMPARE(cell1->text(QAccessible::Name), QString("0.0")); QCOMPARE(iface->indexOfChild(cell1), 5); diff --git a/tests/auto/test.pl b/tests/auto/test.pl deleted file mode 100755 index 4df8c40e9e..0000000000 --- a/tests/auto/test.pl +++ /dev/null @@ -1,223 +0,0 @@ -#!/usr/bin/env perl -############################################################################# -## -## 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$ -## -############################################################################# - -use strict; -use Cwd; -use warnings; - -# Usage: test.pl <SearchPath> <ExecutionMode> <TestResults> <Timeout [Default 300 seconds]> -# Variable declarations to keep strict happy -our $SEARCH_PATH; -our $EXEC_MODE; -our $EXE_PREFIX; -our $EXE_SUFFIX; -our $TIMEOUT; -our $REPORTDIR; -our $buryChildren; -our $timeoutChildren; -our $totalExecuted; -our $totalStarted; -our $totalTimedOut; -our $currentDirectory; -our $testRoot; - -# Where do we run this script? What directory? -$SEARCH_PATH=$ARGV[0]; -if(!$SEARCH_PATH) -{ - print "Please specify the search directory! \n"; - exit(0); -} - -# We have four options: -# 'U': Unix -# 'W': Windows -# 'M': Mac -# 'E': Embedded -$EXEC_MODE=$ARGV[1]; -if($EXEC_MODE =~ /^U$/) -{ - print "Using Unix execution mode\n"; - $EXE_PREFIX="./"; - $EXE_SUFFIX=""; -} elsif($EXEC_MODE =~ /^W$/) -{ - print "Using Windows execution mode\n"; - $EXE_PREFIX=""; - $EXE_SUFFIX=".exe"; -} elsif($EXEC_MODE =~ /^M$/) -{ - print "Using OSX execution mode\n"; - $EXE_PREFIX="/Contents/MacOS/"; - $EXE_SUFFIX=".app"; -} elsif($EXEC_MODE =~ /^E$/) -{ - print "Using embedded execution mode\n"; - $EXE_PREFIX="./"; - $EXE_SUFFIX=""; -} else { - print "Unknown execution mode: $EXEC_MODE \n"; - print "Use: 'U' (Unix), 'W' (Windows), 'M' (MacOSX)\n"; - exit(0); -} -# We get the current directory, we 'll need it afterwards -$currentDirectory = getcwd(); - -$testRoot = Cwd::abs_path($SEARCH_PATH); - -# We assume that by default goes to "reports" unless the user specifies it. -$REPORTDIR = $ARGV[2]; -if(!$REPORTDIR) -{ - $REPORTDIR = $testRoot."/reports"; - mkdir $REPORTDIR; -} else { - mkdir $REPORTDIR; - $REPORTDIR = Cwd::abs_path($REPORTDIR); -} - -# If given we use it, otherwise we default to 300 seconds. -$TIMEOUT = $ARGV[3]; -if(!$TIMEOUT) -{ - $TIMEOUT=300; -} -print "Timeout value: $TIMEOUT\n"; - -# Initialize 'global' variables -$buryChildren = 0; -$timeoutChildren = 0; -$totalExecuted = 0; -$totalStarted = 0; -$totalTimedOut = 0; - -# Install signal handlers and pray for the best -$SIG{'CHLD'} = 'handleDeath'; -$SIG{'ALRM'} = 'handleTimeout'; - -handleDir($testRoot); - -print " ** Statistics ** \n"; -print " Tests started: $totalStarted \n"; -print " Tests executed: $totalExecuted \n"; -print " Tests timed out: $totalTimedOut \n"; - -sub handleDir { - - my ($dir) = @_; - my $currentDir = getcwd(); - - opendir(DIR, $dir); - my @files = readdir(DIR); - closedir DIR; - my $file; - foreach $file (@files) { - #skip hidden files - next if (substr($file,0,1) eq "."); - - if ( -d $dir."/".$file) { - handleDir($dir."/".$file) - } elsif ( $file =~ /^tst_/ and -x $dir."/".$file ) { - chdir($dir) || die("Could not chdir to $dir"); - executeTestCurrentDir($file); - chdir($currentDir); - } - } -} - -sub executeTestCurrentDir { - my ($command) = @_; - print "Executing $command \n"; - my $myPid; - $myPid = fork(); - if($myPid == 0) - { - my $realCommand; - if($EXEC_MODE =~/^M$/) - { - $realCommand = "./".$command.$EXE_SUFFIX.$EXE_PREFIX.$command; - } else { - $realCommand = $EXE_PREFIX.$command.$EXE_SUFFIX; - } - my $outputRedirection = $REPORTDIR."/".$command.$EXE_SUFFIX.".xml"; - - if($EXEC_MODE =~ /^E$/) - { - exec($realCommand, "-qws", "-xml", "-o", $outputRedirection); - } else { - exec($realCommand, "-xml", "-o", $outputRedirection); - } - exit(0); - } elsif($myPid > 0 ) - { - $totalStarted++; - alarm($TIMEOUT); - while(!$buryChildren && !$timeoutChildren) - { - sleep 10; - } - if($buryChildren) - { - my $value; - $value = waitpid($myPid , 0); - $buryChildren = 0; - $totalExecuted++; - } elsif($timeoutChildren) - { - kill 'INT', $myPid; - $timeoutChildren = 0; - $totalTimedOut++; - } else { - # What?? If we get here we need to abort, this is totally unexpected - print "Wrong condition evaluated, aborting to avoid damages\n"; - exit(0); - } - # We need to handle children killed because of timeout - if($buryChildren) - { - my $value; - $value = waitpid($myPid , 0); - $buryChildren = 0; - } - } else { - print "Problems trying to execute $command"; - } - -} - -# This procedure takes care of handling dead children on due time -sub handleDeath { - $buryChildren = 1; -} - -# This takes care of timeouts -sub handleTimeout { - $timeoutChildren = 1; -} - diff --git a/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp b/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp index c9aef497af..44cb5a5bf8 100644 --- a/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp +++ b/tests/auto/widgets/dialogs/qfiledialog/tst_qfiledialog.cpp @@ -119,6 +119,8 @@ private slots: void selectFilter(); void viewMode(); void proxymodel(); + void setMimeTypeFilters_data(); + void setMimeTypeFilters(); void setNameFilter_data(); void setNameFilter(); void setEmptyNameFilter(); @@ -1039,6 +1041,34 @@ void tst_QFiledialog::proxymodel() QCOMPARE(fd.proxyModel(), nullptr); } +void tst_QFiledialog::setMimeTypeFilters_data() +{ + QTest::addColumn<QStringList>("mimeTypeFilters"); + QTest::addColumn<QString>("targetMimeTypeFilter"); + QTest::addColumn<QString>("expectedSelectedMimeTypeFilter"); + + const auto headerMime = QStringLiteral("text/x-chdr"); + const auto jsonMime = QStringLiteral("application/json"); + const auto zipMime = QStringLiteral("application/zip"); + + QTest::newRow("single mime filter (C header file)") << QStringList {headerMime} << headerMime << headerMime; + QTest::newRow("single mime filter (JSON file)") << QStringList {jsonMime} << jsonMime << jsonMime; + QTest::newRow("multiple mime filters") << QStringList {jsonMime, zipMime} << jsonMime << jsonMime; +} + +void tst_QFiledialog::setMimeTypeFilters() +{ + QFETCH(QStringList, mimeTypeFilters); + QFETCH(QString, targetMimeTypeFilter); + QFETCH(QString, expectedSelectedMimeTypeFilter); + + QFileDialog fd; + fd.setMimeTypeFilters(mimeTypeFilters); + fd.selectMimeTypeFilter(targetMimeTypeFilter); + + QCOMPARE(fd.selectedMimeTypeFilter(), expectedSelectedMimeTypeFilter); +} + void tst_QFiledialog::setEmptyNameFilter() { QFileDialog fd; diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp index c8bdcbde09..5ab24d6878 100644 --- a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview.cpp @@ -2885,7 +2885,7 @@ public: void tst_QGraphicsView::scrollBarRanges() { - QFETCH(QString, style); + QFETCH(QByteArray, style); QFETCH(QSize, viewportSize); QFETCH(QRectF, sceneRect); QFETCH(ScrollBarCount, sceneRectOffsetFactors); @@ -2898,7 +2898,7 @@ void tst_QGraphicsView::scrollBarRanges() QFETCH(ExpectedValueDescription, vmax); QFETCH(bool, useStyledPanel); - if (useStyledPanel && style == QStringLiteral("Macintosh") && platformName == QStringLiteral("cocoa")) + if (useStyledPanel && style == "Macintosh" && platformName == QStringLiteral("cocoa")) QSKIP("Insignificant on OSX"); QScopedPointer<QStyle> stylePtr; @@ -2909,10 +2909,10 @@ void tst_QGraphicsView::scrollBarRanges() view.setTransform(transform); view.setFrameStyle(useStyledPanel ? QFrame::StyledPanel : QFrame::NoFrame); - if (style == QString("motif")) + if (style == "motif") stylePtr.reset(new FauxMotifStyle); else - stylePtr.reset(QStyleFactory::create(style)); + stylePtr.reset(QStyleFactory::create(QLatin1String(style))); view.setStyle(stylePtr.data()); view.setStyleSheet(" "); // enables style propagation ;-) diff --git a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview_2.cpp b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview_2.cpp index 875f671e76..9550655868 100644 --- a/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview_2.cpp +++ b/tests/auto/widgets/graphicsview/qgraphicsview/tst_qgraphicsview_2.cpp @@ -44,9 +44,8 @@ Q_DECLARE_METATYPE(QPainterPath) Q_DECLARE_METATYPE(Qt::ScrollBarPolicy) Q_DECLARE_METATYPE(ScrollBarCount) -static void _scrollBarRanges_addTestData(const QString &style, bool styled) +static void _scrollBarRanges_addTestData(const QByteArray &style, bool styled) { - const QString styleString = styled ? style + ", Styled" : style; const int viewWidth = 250; const int viewHeight = 100; @@ -59,7 +58,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription hmin, hmax, vmin, vmax; } data [] = { { - ", 1", + "1", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -71,7 +70,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 2", + "2", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -83,7 +82,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 3", + "3", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -95,7 +94,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 1, 1), }, { - ", 4", + "4", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -107,7 +106,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 5", + "5", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -119,7 +118,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 6", + "6", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -131,7 +130,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 7", + "7", QRectF(0, 0, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -143,7 +142,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1, 1, 1), }, { - ", 8", + "8", QRectF(0, 0, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -155,7 +154,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1, 1, 1), }, { - ", 9", + "9", QRectF(0, 0, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -167,7 +166,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(101, 1, 1), }, { - ", 10", + "10", QRectF(-101, -101, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -179,7 +178,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 11", + "11", QRectF(-101, -101, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -191,7 +190,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 12", + "12", QRectF(-101, -101, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -203,7 +202,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 13", + "13", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -215,7 +214,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 2, 1), }, { - ", 14", + "14", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -227,7 +226,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 2, 1), }, { - ", 15", + "15", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 1, 1), 1, @@ -239,7 +238,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 2, 1), }, { - ", 16", + "16", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -251,7 +250,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 17", + "17", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -263,7 +262,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 18", + "18", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(-1, -1, 1, 1), 1, @@ -275,7 +274,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 1 x2", + "1 x2", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -287,7 +286,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 2 x2", + "2 x2", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -299,7 +298,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 3 x2", + "3 x2", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -311,7 +310,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight + 200, 1, 1), }, { - ", 4 x2", + "4 x2", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -323,7 +322,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200, 1, 1), }, { - ", 5 x2", + "5 x2", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -335,7 +334,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200, 1, 1), }, { - ", 6 x2", + "6 x2", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -347,7 +346,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 1 No ScrollBars", + "1 No ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -359,7 +358,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 2 No ScrollBars", + "2 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -371,7 +370,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 3 No ScrollBars", + "3 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -383,7 +382,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100), }, { - ", 4 No ScrollBars", + "4 No ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -395,7 +394,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 5 No ScrollBars", + "5 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -407,7 +406,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 6 No ScrollBars", + "6 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -419,7 +418,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 7 No ScrollBars", + "7 No ScrollBars", QRectF(0, 0, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -431,7 +430,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1), }, { - ", 8 No ScrollBars", + "8 No ScrollBars", QRectF(0, 0, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -443,7 +442,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1), }, { - ", 9 No ScrollBars", + "9 No ScrollBars", QRectF(0, 0, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -455,7 +454,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(101), }, { - ", 10 No ScrollBars", + "10 No ScrollBars", QRectF(-101, -101, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -467,7 +466,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 11 No ScrollBars", + "11 No ScrollBars", QRectF(-101, -101, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -479,7 +478,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 12 No ScrollBars", + "12 No ScrollBars", QRectF(-101, -101, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -491,7 +490,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 13 No ScrollBars", + "13 No ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -503,7 +502,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1), }, { - ", 14 No ScrollBars", + "14 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -515,7 +514,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1), }, { - ", 15 No ScrollBars", + "15 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 1, 1), 1, @@ -527,7 +526,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 1), }, { - ", 16 No ScrollBars", + "16 No ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -539,7 +538,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 17 No ScrollBars", + "17 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -551,7 +550,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 18 No ScrollBars", + "18 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(-1, -1, 1, 1), 1, @@ -563,7 +562,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 1 x2 No ScrollBars", + "1 x2 No ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -575,7 +574,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight), }, { - ", 2 x2 No ScrollBars", + "2 x2 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -587,7 +586,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight), }, { - ", 3 x2 No ScrollBars", + "3 x2 No ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -599,7 +598,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight + 200), }, { - ", 4 x2 No ScrollBars", + "4 x2 No ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -611,7 +610,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200), }, { - ", 5 x2 No ScrollBars", + "5 x2 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -623,7 +622,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200), }, { - ", 6 x2 No ScrollBars", + "6 x2 No ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -635,7 +634,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight), }, { - ", 1 Always ScrollBars", + "1 Always ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -647,7 +646,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 2 Always ScrollBars", + "2 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -659,7 +658,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 3 Always ScrollBars", + "3 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -671,7 +670,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 1, 1), }, { - ", 4 Always ScrollBars", + "4 Always ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -683,7 +682,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 5 Always ScrollBars", + "5 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -695,7 +694,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 6 Always ScrollBars", + "6 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -707,7 +706,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 7 Always ScrollBars", + "7 Always ScrollBars", QRectF(0, 0, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -719,7 +718,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1, 1, 1), }, { - ", 8 Always ScrollBars", + "8 Always ScrollBars", QRectF(0, 0, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -731,7 +730,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1, 1, 1), }, { - ", 9 Always ScrollBars", + "9 Always ScrollBars", QRectF(0, 0, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -743,7 +742,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(101, 1, 1), }, { - ", 10 Always ScrollBars", + "10 Always ScrollBars", QRectF(-101, -101, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -755,7 +754,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 11 Always ScrollBars", + "11 Always ScrollBars", QRectF(-101, -101, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -767,7 +766,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 12 Always ScrollBars", + "12 Always ScrollBars", QRectF(-101, -101, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -779,7 +778,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 13 Always ScrollBars", + "13 Always ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -791,7 +790,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 2, 1), }, { - ", 14 Always ScrollBars", + "14 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -803,7 +802,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 2, 1), }, { - ", 15 Always ScrollBars", + "15 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 1, 1), 1, @@ -815,7 +814,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 2, 1), }, { - ", 16 Always ScrollBars", + "16 Always ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -827,7 +826,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 17 Always ScrollBars", + "17 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -839,7 +838,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100, 1, 1), }, { - ", 18 Always ScrollBars", + "18 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(-1, -1, 1, 1), 1, @@ -851,7 +850,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1, 1), }, { - ", 1 x2 Always ScrollBars", + "1 x2 Always ScrollBars", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -863,7 +862,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 2 x2 Always ScrollBars", + "2 x2 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -875,7 +874,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 3 x2 Always ScrollBars", + "3 x2 Always ScrollBars", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -887,7 +886,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight + 200, 1, 1), }, { - ", 4 x2 Always ScrollBars", + "4 x2 Always ScrollBars", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -899,7 +898,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200, 1, 1), }, { - ", 5 x2 Always ScrollBars", + "5 x2 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -911,7 +910,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200, 1, 1), }, { - ", 6 x2 Always ScrollBars", + "6 x2 Always ScrollBars", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -923,7 +922,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight, 1, 1), }, { - ", 1 Vertical Only", + "1 Vertical Only", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -935,7 +934,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 2 Vertical Only", + "2 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -947,7 +946,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 3 Vertical Only", + "3 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -959,7 +958,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100), }, { - ", 4 Vertical Only", + "4 Vertical Only", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -971,7 +970,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 5 Vertical Only", + "5 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 1, @@ -983,7 +982,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 6 Vertical Only", + "6 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 1, @@ -995,7 +994,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 7 Vertical Only", + "7 Vertical Only", QRectF(0, 0, viewWidth + 1, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -1007,7 +1006,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1), }, { - ", 8 Vertical Only", + "8 Vertical Only", QRectF(0, 0, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -1019,7 +1018,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(1), }, { - ", 9 Vertical Only", + "9 Vertical Only", QRectF(0, 0, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -1031,7 +1030,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(101), }, { - ", 10 Vertical Only", + "10 Vertical Only", QRectF(-101, -101, viewWidth + 1, viewHeight +1), ScrollBarCount(0, 0, 0, 0), 1, @@ -1043,7 +1042,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 11 Vertical Only", + "11 Vertical Only", QRectF(-101, -101, viewWidth + 51, viewHeight + 1), ScrollBarCount(0, 0, 0, 0), 1, @@ -1055,7 +1054,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 12 Vertical Only", + "12 Vertical Only", QRectF(-101, -101, viewWidth + 51, viewHeight + 101), ScrollBarCount(0, 0, 0, 0), 1, @@ -1067,7 +1066,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 13 Vertical Only", + "13 Vertical Only", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -1079,7 +1078,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1), }, { - ", 14 Vertical Only", + "14 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 1, 1), 1, @@ -1091,7 +1090,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(0, 1), }, { - ", 15 Vertical Only", + "15 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 1, 1), 1, @@ -1103,7 +1102,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(100, 1), }, { - ", 16 Vertical Only", + "16 Vertical Only", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -1115,7 +1114,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 17 Vertical Only", + "17 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(-1, -1, 1, 1), 1, @@ -1127,7 +1126,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(-100), }, { - ", 18 Vertical Only", + "18 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(-1, -1, 1, 1), 1, @@ -1139,7 +1138,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(), }, { - ", 1 x2 Vertical Only", + "1 x2 Vertical Only", QRectF(0, 0, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -1151,7 +1150,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight), }, { - ", 2 x2 Vertical Only", + "2 x2 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -1163,7 +1162,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight), }, { - ", 3 x2 Vertical Only", + "3 x2 Vertical Only", QRectF(0, 0, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -1175,7 +1174,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight + 200), }, { - ", 4 x2 Vertical Only", + "4 x2 Vertical Only", QRectF(-100, -100, viewWidth, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -1187,7 +1186,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200), }, { - ", 5 x2 Vertical Only", + "5 x2 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight), ScrollBarCount(0, 0, 0, 0), 2, @@ -1199,7 +1198,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) ExpectedValueDescription(viewHeight - 200), }, { - ", 6 x2 Vertical Only", + "6 x2 Vertical Only", QRectF(-100, -100, viewWidth + 50, viewHeight + 100), ScrollBarCount(0, 0, 0, 0), 2, @@ -1215,7 +1214,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) const QSize viewSize(viewWidth, viewHeight); for (const Data &e : data) { - QTest::newRow(qPrintable(styleString + QLatin1String(e.name))) + QTest::addRow("%s%s, %s", style.data(), styled ? ", Styled" : "", e.name) << style << viewSize << e.sceneRect << e.sceneRectOffsetFactors @@ -1229,7 +1228,7 @@ static void _scrollBarRanges_addTestData(const QString &style, bool styled) void _scrollBarRanges_data() { - QTest::addColumn<QString>("style"); + QTest::addColumn<QByteArray>("style"); QTest::addColumn<QSize>("viewportSize"); QTest::addColumn<QRectF>("sceneRect"); QTest::addColumn<ScrollBarCount>("sceneRectOffsetFactors"); @@ -1242,14 +1241,15 @@ void _scrollBarRanges_data() QTest::addColumn<ExpectedValueDescription>("vmax"); QTest::addColumn<bool>("useStyledPanel"); - foreach (const QString &style, QStyleFactory::keys()) { - _scrollBarRanges_addTestData(style, false); - _scrollBarRanges_addTestData(style, true); + const auto styles = QStyleFactory::keys(); + for (const QString &style : styles) { + _scrollBarRanges_addTestData(style.toLatin1(), false); + _scrollBarRanges_addTestData(style.toLatin1(), true); } const QScreen *screen = QGuiApplication::primaryScreen(); if (screen && qFuzzyCompare((double)screen->logicalDotsPerInchX(), 96.0)) { - _scrollBarRanges_addTestData(QString("motif"), false); - _scrollBarRanges_addTestData(QString("motif"), true); + _scrollBarRanges_addTestData("motif", false); + _scrollBarRanges_addTestData("motif", true); } } diff --git a/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp b/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp index a89f8f3c8a..29e4bbfe29 100644 --- a/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp +++ b/tests/auto/widgets/itemviews/qlistview/tst_qlistview.cpp @@ -150,6 +150,7 @@ private slots: void horizontalScrollingByVerticalWheelEvents(); void taskQTBUG_7232_AllowUserToControlSingleStep(); void taskQTBUG_51086_skippingIndexesInSelectedIndexes(); + void expandingListItems(); void taskQTBUG_47694_indexOutOfBoundBatchLayout(); }; @@ -2487,6 +2488,29 @@ void tst_QListView::taskQTBUG_51086_skippingIndexesInSelectedIndexes() QVERIFY(!indexes.contains(data.index(8, 0))); } +void tst_QListView::expandingListItems() +{ + auto item1 = new QStandardItem("111"); + auto item2 = new QStandardItem("111111"); + QStandardItemModel model; + model.appendRow(item1); + model.appendRow(item2); + + QListView w; + w.setModel(&model); + w.setWrapping(true); + w.show(); + QVERIFY(QTest::qWaitForWindowExposed(&w)); + + QVERIFY(w.visualRect(item1->index()).width() > 0); + QVERIFY(w.visualRect(item1->index()).width() == w.visualRect(item2->index()).width()); + + w.setExpandingListItems(false); + QApplication::processEvents(); + + QVERIFY(w.visualRect(item1->index()).width() < w.visualRect(item2->index()).width()); +} + void tst_QListView::taskQTBUG_47694_indexOutOfBoundBatchLayout() { QListView view; diff --git a/tests/auto/widgets/kernel/qapplication/test/test.pro b/tests/auto/widgets/kernel/qapplication/test/test.pro index 92409e4bfe..7f75501474 100644 --- a/tests/auto/widgets/kernel/qapplication/test/test.pro +++ b/tests/auto/widgets/kernel/qapplication/test/test.pro @@ -1,5 +1,5 @@ CONFIG += testcase -CONFIG -= app_bundle debug_and_release_target +CONFIG -= debug_and_release_target QT += widgets widgets-private testlib QT += core-private gui-private diff --git a/tests/auto/widgets/kernel/qsizepolicy/qsizepolicy.pro b/tests/auto/widgets/kernel/qsizepolicy/qsizepolicy.pro index 84629c7c0a..d325bc4aeb 100644 --- a/tests/auto/widgets/kernel/qsizepolicy/qsizepolicy.pro +++ b/tests/auto/widgets/kernel/qsizepolicy/qsizepolicy.pro @@ -1,4 +1,5 @@ CONFIG += testcase +contains(QT_CONFIG, c++14): CONFIG += c++14 TARGET = tst_qsizepolicy QT += widgets widgets-private testlib diff --git a/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp b/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp index 9e5fc55379..98b765a6c6 100644 --- a/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp +++ b/tests/auto/widgets/kernel/qsizepolicy/tst_qsizepolicy.cpp @@ -41,9 +41,12 @@ class tst_QSizePolicy : public QObject private Q_SLOTS: void cleanup() { QVERIFY(QApplication::topLevelWidgets().isEmpty()); } void qtest(); + void constExpr(); void defaultValues(); void getSetCheck_data() { data(); } void getSetCheck(); + void transposed_data() { data(); } + void transposed(); void dataStream(); void horizontalStretch(); void verticalStretch(); @@ -102,6 +105,19 @@ void tst_QSizePolicy::qtest() #undef CHECK2 } +void tst_QSizePolicy::constExpr() +{ +/* gcc < 4.8.0 has problems with init'ing variant members in constexpr ctors */ +/* https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54922 */ +#if !defined(Q_CC_GNU) || defined(Q_CC_INTEL) || defined(Q_CC_CLANG) || Q_CC_GNU >= 408 + // check that certain ctors are constexpr (compile-only): + { Q_CONSTEXPR QSizePolicy sp; Q_UNUSED(sp); } + { Q_CONSTEXPR QSizePolicy sp = QSizePolicy(); Q_UNUSED(sp); } +#else + QSKIP("QSizePolicy cannot be constexpr with this version of the compiler."); +#endif +} + void tst_QSizePolicy::defaultValues() { { @@ -147,14 +163,34 @@ void tst_QSizePolicy::getSetCheck() QCOMPARE(sp.expandingDirections(), ed); } +void tst_QSizePolicy::transposed() +{ + FETCH_TEST_DATA; + + const QSizePolicy tr = sp.transposed(); + + QCOMPARE(tr.horizontalPolicy(), vp); // swapped + QCOMPARE(tr.verticalPolicy(), hp); // swapped + QCOMPARE(tr.horizontalStretch(), vst); // swapped + QCOMPARE(tr.verticalStretch(), hst); // swapped + QCOMPARE(tr.controlType(), ct); // not swapped + QCOMPARE(tr.hasHeightForWidth(), hfw); // not swapped (historic behavior) + QCOMPARE(tr.hasWidthForHeight(), wfh); // not swapped (historic behavior) + QCOMPARE(tr.expandingDirections(), ed); // swapped + + // destructive test - keep last: + sp.transpose(); + QCOMPARE(sp, tr); +} + static void makeRow(QSizePolicy sp, QSizePolicy::Policy hp, QSizePolicy::Policy vp, int hst, int vst, QSizePolicy::ControlType ct, bool hfw, bool wfh, Qt::Orientations orients) { - QTest::newRow(qPrintable(QString::asprintf("%s-%s-%d-%d-%s-%s-%s", - PrettyPrint(hp).s(), PrettyPrint(vp).s(), hst, vst, - PrettyPrint(ct).s(), - hfw ? "true" : "false", wfh ? "true" : "false"))) + QTest::addRow("%s-%s-%d-%d-%s-%s-%s", + PrettyPrint(hp).s(), PrettyPrint(vp).s(), hst, vst, + PrettyPrint(ct).s(), + hfw ? "true" : "false", wfh ? "true" : "false") << sp << hp << vp << hst << vst << ct << hfw << wfh << orients; } diff --git a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp index 731a8c5d91..2657b28d30 100644 --- a/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp +++ b/tests/auto/widgets/kernel/qwidget/tst_qwidget.cpp @@ -4243,12 +4243,14 @@ void tst_QWidget::update() } } +#ifndef Q_OS_OSX static inline bool isOpaque(QWidget *widget) { if (!widget) return false; return qt_widget_private(widget)->isOpaque; } +#endif void tst_QWidget::isOpaque() { @@ -5214,16 +5216,40 @@ protected: widgetDuringFocusAboutToChange = qApp->focusWidget(); return QWidget::event(ev); } + virtual void focusInEvent(QFocusEvent *) + { + foucsObjectDuringFocusIn = qApp->focusObject(); + detectedBadEventOrdering = foucsObjectDuringFocusIn != mostRecentFocusObjectChange; + } virtual void focusOutEvent(QFocusEvent *) { + foucsObjectDuringFocusOut = qApp->focusObject(); widgetDuringFocusOut = qApp->focusWidget(); + detectedBadEventOrdering = foucsObjectDuringFocusOut != mostRecentFocusObjectChange; + } + + void focusObjectChanged(QObject *focusObject) + { + mostRecentFocusObjectChange = focusObject; } public: - FocusWidget(QWidget *parent) : QWidget(parent), widgetDuringFocusAboutToChange(0), widgetDuringFocusOut(0) {} + FocusWidget(QWidget *parent) : QWidget(parent), + widgetDuringFocusAboutToChange(0), widgetDuringFocusOut(0), + foucsObjectDuringFocusIn(0), foucsObjectDuringFocusOut(0), + mostRecentFocusObjectChange(0), detectedBadEventOrdering(false) + { + connect(qGuiApp, &QGuiApplication::focusObjectChanged, this, &FocusWidget::focusObjectChanged); + } QWidget *widgetDuringFocusAboutToChange; QWidget *widgetDuringFocusOut; + + QObject *foucsObjectDuringFocusIn; + QObject *foucsObjectDuringFocusOut; + + QObject *mostRecentFocusObjectChange; + bool detectedBadEventOrdering; }; void tst_QWidget::setFocus() @@ -5424,6 +5450,40 @@ void tst_QWidget::setFocus() QCOMPARE(window.focusWidget(), nullptr); QCOMPARE(QApplication::focusWidget(), nullptr); } + + { + QWidget window; + window.resize(m_testWidgetSize); + window.move(windowPos); + + FocusWidget child1(&window); + QWidget child2(&window); + + window.show(); + window.activateWindow(); + QVERIFY(QTest::qWaitForWindowExposed(&window)); + QTRY_VERIFY(QApplication::focusWindow()); + + QCOMPARE(QApplication::focusObject(), &window); + + child1.setFocus(); + QTRY_VERIFY(child1.hasFocus()); + QCOMPARE(window.focusWidget(), &child1); + QCOMPARE(QApplication::focusWidget(), &child1); + QCOMPARE(QApplication::focusObject(), &child1); + QCOMPARE(child1.foucsObjectDuringFocusIn, &child1); + QVERIFY2(!child1.detectedBadEventOrdering, + "focusObjectChanged should be delivered before widget focus events on setFocus"); + + child1.clearFocus(); + QTRY_VERIFY(!child1.hasFocus()); + QCOMPARE(window.focusWidget(), nullptr); + QCOMPARE(QApplication::focusWidget(), nullptr); + QCOMPARE(QApplication::focusObject(), &window); + QVERIFY(child1.foucsObjectDuringFocusOut != &child1); + QVERIFY2(!child1.detectedBadEventOrdering, + "focusObjectChanged should be delivered before widget focus events on clearFocus"); + } } template<class T> class EventSpy : public QObject @@ -8957,8 +9017,13 @@ void tst_QWidget::taskQTBUG_4055_sendSyntheticEnterLeave() void tst_QWidget::windowFlags() { QWidget w; + const auto baseFlags = w.windowFlags(); w.setWindowFlags(w.windowFlags() | Qt::FramelessWindowHint); QVERIFY(w.windowFlags() & Qt::FramelessWindowHint); + w.setWindowFlag(Qt::WindowStaysOnTopHint, true); + QCOMPARE(w.windowFlags(), baseFlags | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint); + w.setWindowFlag(Qt::FramelessWindowHint, false); + QCOMPARE(w.windowFlags(), baseFlags | Qt::WindowStaysOnTopHint); } void tst_QWidget::initialPosForDontShowOnScreenWidgets() diff --git a/tests/auto/widgets/kernel/qwindowcontainer/qwindowcontainer.pro b/tests/auto/widgets/kernel/qwindowcontainer/qwindowcontainer.pro index 17fc1d28b5..50069b7e3e 100644 --- a/tests/auto/widgets/kernel/qwindowcontainer/qwindowcontainer.pro +++ b/tests/auto/widgets/kernel/qwindowcontainer/qwindowcontainer.pro @@ -1,5 +1,4 @@ CONFIG += testcase -mac:CONFIG -= app_bundle TARGET = tst_qwindowcontainer QT += widgets testlib SOURCES += tst_qwindowcontainer.cpp diff --git a/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp b/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp index 92a8dff218..937be944a1 100644 --- a/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp +++ b/tests/auto/widgets/util/qcompleter/tst_qcompleter.cpp @@ -1193,7 +1193,7 @@ void tst_QCompleter::disabledItems() model->appendRow(suggestions); model->appendRow(new QStandardItem("suggestions Enabled")); QCompleter *completer = new QCompleter(model, &lineEdit); - QSignalSpy spy(completer, SIGNAL(activated(QString))); + QSignalSpy spy(completer, QOverload<const QString &>::of(&QCompleter::activated)); lineEdit.setCompleter(completer); lineEdit.move(200, 200); lineEdit.show(); @@ -1219,7 +1219,7 @@ void tst_QCompleter::task178797_activatedOnReturn() setFrameless(&ledit); QCompleter *completer = new QCompleter(words, &ledit); ledit.setCompleter(completer); - QSignalSpy spy(completer, SIGNAL(activated(QString))); + QSignalSpy spy(completer, QOverload<const QString &>::of(&QCompleter::activated)); QCOMPARE(spy.count(), 0); ledit.move(200, 200); ledit.show(); @@ -1287,7 +1287,7 @@ public: if (completer()) { completer()->setCompletionMode(QCompleter::PopupCompletion); completer()->setCompletionRole(Qt::DisplayRole); - connect(lineEdit(), SIGNAL(editingFinished()), SLOT(setCompletionPrefix())); + connect(lineEdit(), &QLineEdit::editingFinished, this, &task246056_ComboBox::setCompletionPrefix); } } private slots: @@ -1306,7 +1306,7 @@ void tst_QCompleter::task246056_setCompletionPrefix() comboBox.show(); QApplication::setActiveWindow(&comboBox); QVERIFY(QTest::qWaitForWindowActive(&comboBox)); - QSignalSpy spy(comboBox.completer(), SIGNAL(activated(QModelIndex))); + QSignalSpy spy(comboBox.completer(), QOverload<const QModelIndex &>::of(&QCompleter::activated)); QTest::keyPress(&comboBox, 'a'); QTest::keyPress(comboBox.completer()->popup(), Qt::Key_Down); QTest::keyPress(comboBox.completer()->popup(), Qt::Key_Down); diff --git a/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp b/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp index 616898c4c5..5acaf49e6c 100644 --- a/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp +++ b/tests/auto/widgets/util/qsystemtrayicon/tst_qsystemtrayicon.cpp @@ -118,7 +118,7 @@ void tst_QSystemTrayIcon::supportsMessages() void tst_QSystemTrayIcon::lastWindowClosed() { - QSignalSpy spy(qApp, SIGNAL(lastWindowClosed())); + QSignalSpy spy(qApp, &QApplication::lastWindowClosed); QWidget window; QSystemTrayIcon icon; icon.setIcon(QIcon("whatever.png")); diff --git a/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp b/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp index f5cf9d7750..7641ea6b68 100644 --- a/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp +++ b/tests/auto/widgets/util/qundogroup/tst_qundogroup.cpp @@ -379,12 +379,12 @@ void tst_QUndoGroup::checkSignals() QUndoGroup group; const QScopedPointer<QAction> undo_action(group.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redo_action(group.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&group, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&group, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&group, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&group, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&group, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&group, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&group, &QUndoGroup::indexChanged); + QSignalSpy cleanChangedSpy(&group, &QUndoGroup::cleanChanged); + QSignalSpy canUndoChangedSpy(&group, &QUndoGroup::canUndoChanged); + QSignalSpy undoTextChangedSpy(&group, &QUndoGroup::undoTextChanged); + QSignalSpy canRedoChangedSpy(&group, &QUndoGroup::canRedoChanged); + QSignalSpy redoTextChangedSpy(&group, &QUndoGroup::redoTextChanged); QString str; diff --git a/tests/auto/widgets/util/qundostack/tst_qundostack.cpp b/tests/auto/widgets/util/qundostack/tst_qundostack.cpp index a3e7219892..11a29b808c 100644 --- a/tests/auto/widgets/util/qundostack/tst_qundostack.cpp +++ b/tests/auto/widgets/util/qundostack/tst_qundostack.cpp @@ -95,6 +95,23 @@ public: virtual void redo(); }; +class MoveMouseCommand : public QUndoCommand +{ +public: + MoveMouseCommand(QPoint *mouse, QPoint oldPoint, QPoint newPoint, QUndoCommand *parent = 0); + ~MoveMouseCommand(); + + virtual void undo(); + virtual void redo(); + virtual int id() const; + virtual bool mergeWith(const QUndoCommand *other); + +private: + QPoint *m_mouse; + QPoint m_oldPoint; + QPoint m_newPoint; +}; + InsertCommand::InsertCommand(QString *str, int idx, const QString &text, QUndoCommand *parent) : QUndoCommand(parent) @@ -215,6 +232,48 @@ void IdleCommand::undo() { } +MoveMouseCommand::MoveMouseCommand(QPoint *mouse, QPoint oldPoint, QPoint newPoint, QUndoCommand *parent) + : QUndoCommand(parent) +{ + setText("move mouse"); + + m_mouse = mouse; + m_oldPoint = oldPoint; + m_newPoint = newPoint; + + if (m_oldPoint == m_newPoint) + setObsolete(true); +} + +MoveMouseCommand::~MoveMouseCommand() +{ +} + +void MoveMouseCommand::redo() +{ + *m_mouse = m_newPoint; +} + +void MoveMouseCommand::undo() +{ + *m_mouse = m_oldPoint; +} + +int MoveMouseCommand::id() const +{ + return 2; +} + +bool MoveMouseCommand::mergeWith(const QUndoCommand *other) +{ + m_newPoint = static_cast<const MoveMouseCommand*>(other)->m_newPoint; + + if (m_newPoint == m_oldPoint) + setObsolete(true); + + return true; +} + /****************************************************************************** ** tst_QUndoStack */ @@ -233,6 +292,7 @@ private slots: void childCommand(); void macroBeginEnd(); void compression(); + void obsolete(); void undoLimit(); void commandTextFormat(); void separateUndoText(); @@ -329,12 +389,12 @@ void tst_QUndoStack::undoRedo() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; // push, undo, redo @@ -690,12 +750,12 @@ void tst_QUndoStack::setIndex() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; stack.setIndex(10); // should do nothing @@ -954,12 +1014,12 @@ void tst_QUndoStack::setClean() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; QCOMPARE(stack.cleanIndex(), 0); @@ -1351,12 +1411,12 @@ void tst_QUndoStack::clear() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; stack.clear(); @@ -1549,12 +1609,12 @@ void tst_QUndoStack::childCommand() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; stack.push(new InsertCommand(&str, 0, "hello")); @@ -1659,12 +1719,12 @@ void tst_QUndoStack::macroBeginEnd() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; stack.beginMacro("ding"); @@ -2126,12 +2186,12 @@ void tst_QUndoStack::compression() QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); QString str; AppendCommand::delete_cnt = 0; @@ -2563,17 +2623,722 @@ void tst_QUndoStack::compression() true); // redoChanged } +void tst_QUndoStack::obsolete() +{ + QUndoStack stack; + const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); + const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); + QPoint mouse(0, 0); + QString str; + MoveMouseCommand *cmd1 = 0; + MoveMouseCommand *cmd2 = 0; + + stack.resetClean(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 0, // count + 0, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + true, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(0, 0))); // #1 should not merge but will be deleted (b/c oldPoint == newPoint) + QCOMPARE(mouse, QPoint(0, 0)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 0, // count + 0, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(12, 0))); // #2 should not merge or be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(12, 0)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 1, // count + 1, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(8, 2))); // #3 should merge and not be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(8, 2)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 1, // count + 1, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(0, 0))); // #4 should merge and be deleted (b/c oldPoint == newPoint) + QCOMPARE(mouse, QPoint(0, 0)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 0, // count + 0, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + + + + stack.push(new InsertCommand(&str, 0, "ene")); // #5 should not merge or be deleted + QCOMPARE(str, QString("ene")); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 1, // count + 1, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + cmd1 = new MoveMouseCommand(&mouse, mouse, QPoint(6, 5)); + stack.push(cmd1); // #6 should not merge or be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(6, 5)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 2, // count + 2, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.push(new InsertCommand(&str, 3, "ma")); // #7 should not merge or be deleted + QCOMPARE(str, QString("enema")); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 3, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + cmd2 = new MoveMouseCommand(&mouse, mouse, QPoint(12, 4)); + stack.push(cmd2); // #8 should not merge or be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(12, 4)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 4, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.setClean(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + true, // clean + 4, // count + 4, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + true, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + QCOMPARE(stack.cleanIndex(), 4); + + cmd2->setObsolete(true); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + true, // clean + 4, // count + 4, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.undo(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 3, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + true, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + QCOMPARE(stack.cleanIndex(), -1); + + stack.undo(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 2, // index + true, // canUndo + "move mouse", // undoText + true, // canRedo + "insert", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.setClean(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + true, // clean + 3, // count + 2, // index + true, // canUndo + "move mouse", // undoText + true, // canRedo + "insert", // redoText + true, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + QCOMPARE(stack.cleanIndex(), 2); + + stack.undo(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 1, // index + true, // canUndo + "insert", // undoText + true, // canRedo + "move mouse", // redoText + true, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + cmd1->setObsolete(true); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 1, // index + true, // canUndo + "insert", // undoText + true, // canRedo + "move mouse", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.redo(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 2, // count + 1, // index + true, // canUndo + "insert", // undoText + true, // canRedo + "insert", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + QCOMPARE(stack.cleanIndex(), -1); + + stack.redo(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 2, // count + 2, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + QCOMPARE(stack.cleanIndex(), -1); + + cmd1 = new MoveMouseCommand(&mouse, mouse, QPoint(13, 2)); + stack.push(cmd1); // #9 should not merge or be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(13, 2)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 3, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.push(new InsertCommand(&str, 3, "ma")); // #10 should not merge or be deleted + QCOMPARE(str, QString("enemama")); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 4, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + cmd2 = new MoveMouseCommand(&mouse, mouse, QPoint(6, 20)); + stack.push(cmd2); // #11 should not merge or be deleted (b/c oldPoint != newPoint) + QCOMPARE(mouse, QPoint(6, 20)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 5, // count + 5, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + cmd1->setObsolete(true); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 5, // count + 5, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.setClean(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + true, // clean + 5, // count + 5, // index + true, // canUndo + "move mouse", // undoText + false, // canRedo + "", // redoText + true, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + QCOMPARE(stack.cleanIndex(), 5); + + stack.setIndex(0); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 0, // index + false, // canUndo + "", // undoText + true, // canRedo + "insert", // redoText + true, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + QCOMPARE(stack.cleanIndex(), -1); + + cmd2->setObsolete(true); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 0, // index + false, // canUndo + "", // undoText + true, // canRedo + "insert", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.setIndex(stack.count()); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 3, // count + 3, // index + true, // canUndo + "insert", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged + + mouse = QPoint(0, 0); // Reset mouse position + stack.beginMacro("ding"); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 3, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + true, // undoChanged + true); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(7, 7))); // #12 should not merge or be deleted (b/c oldPoint != newPoint & in macro) + QCOMPARE(mouse, QPoint(7, 7)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 3, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.push(new MoveMouseCommand(&mouse, mouse, QPoint(0, 0))); // #13 should merge and be deleted (b/c oldPoint = newPoint) + QCOMPARE(mouse, QPoint(0, 0)); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 3, // index + false, // canUndo + "", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + false, // indexChanged + false, // undoChanged + false); // redoChanged + + stack.endMacro(); + checkState(redoTextChangedSpy, + canRedoChangedSpy, + undoTextChangedSpy, + redoAction, + undoAction, + canUndoChangedSpy, + cleanChangedSpy, + indexChangedSpy, + stack, + false, // clean + 4, // count + 4, // index + true, // canUndo + "ding", // undoText + false, // canRedo + "", // redoText + false, // cleanChanged + true, // indexChanged + true, // undoChanged + true); // redoChanged +} + void tst_QUndoStack::undoLimit() { QUndoStack stack; const QScopedPointer<QAction> undoAction(stack.createUndoAction(0, QString("foo"))); const QScopedPointer<QAction> redoAction(stack.createRedoAction(0, QString("bar"))); - QSignalSpy indexChangedSpy(&stack, SIGNAL(indexChanged(int))); - QSignalSpy cleanChangedSpy(&stack, SIGNAL(cleanChanged(bool))); - QSignalSpy canUndoChangedSpy(&stack, SIGNAL(canUndoChanged(bool))); - QSignalSpy undoTextChangedSpy(&stack, SIGNAL(undoTextChanged(QString))); - QSignalSpy canRedoChangedSpy(&stack, SIGNAL(canRedoChanged(bool))); - QSignalSpy redoTextChangedSpy(&stack, SIGNAL(redoTextChanged(QString))); + QSignalSpy indexChangedSpy(&stack, &QUndoStack::indexChanged); + QSignalSpy cleanChangedSpy(&stack, &QUndoStack::cleanChanged); + QSignalSpy canUndoChangedSpy(&stack, &QUndoStack::canUndoChanged); + QSignalSpy undoTextChangedSpy(&stack, &QUndoStack::undoTextChanged); + QSignalSpy canRedoChangedSpy(&stack, &QUndoStack::canRedoChanged); + QSignalSpy redoTextChangedSpy(&stack, &QUndoStack::redoTextChanged); AppendCommand::delete_cnt = 0; QString str; diff --git a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp index e3af0135e7..4d57b85f9a 100644 --- a/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp +++ b/tests/auto/widgets/widgets/qmenubar/tst_qmenubar.cpp @@ -119,6 +119,7 @@ private slots: #if !defined(Q_OS_DARWIN) void check_shortcutPress(); void check_menuPosition(); + void taskQTBUG46812_doNotLeaveMenubarHighlighted(); #endif void task223138_triggered(); void task256322_highlight(); @@ -231,9 +232,14 @@ TestMenu tst_QMenuBar::initSimpleMenuBar(QMenuBar *mb, bool forceNonNative) { menu = mb->addMenu(QStringLiteral("accel1")); action = menu->addAction(QStringLiteral("&Open...") ); action->setShortcut(Qt::Key_O); + result.actions << action; + + action = menu->addAction(QStringLiteral("action")); + action->setShortcut(QKeySequence(Qt::ALT + Qt::Key_Z)); + result.actions << action; + result.menus << menu; connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(onSimpleActivated(QAction*))); - result.actions << action; m_lastSimpleAcceleratorId = 0; m_simpleActivatedCount = 0; @@ -319,7 +325,7 @@ inline TestMenu tst_QMenuBar::initWindowWithComplexMenuBar(QMainWindow &w) return initComplexMenuBar(w.menuBar()); } -// On Mac/WinCE, native key events are needed to test menu action activation +// On Mac native key events are needed to test menu action activation #if !defined(Q_OS_DARWIN) void tst_QMenuBar::accel() { @@ -337,7 +343,7 @@ void tst_QMenuBar::accel() } #endif -// On Mac/WinCE, native key events are needed to test menu action activation +// On Mac native key events are needed to test menu action activation #if !defined(Q_OS_DARWIN) void tst_QMenuBar::activatedCount() { @@ -536,7 +542,7 @@ void tst_QMenuBar::insertItem_QString_QObject() QVERIFY(actions.size() < 4); // there is no menu 4! } -// On Mac/WinCE, native key events are needed to test menu action activation +// On Mac native key events are needed to test menu action activation #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_accelKeys() { @@ -609,7 +615,7 @@ void tst_QMenuBar::check_accelKeys() } #endif -// On Mac/WinCE, native key events are needed to test menu action activation +// On Mac native key events are needed to test menu action activation #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_cursorKeys1() { @@ -643,7 +649,7 @@ void tst_QMenuBar::check_cursorKeys1() } #endif -// Qt/Mac,WinCE does not use the native popups/menubar +// Qt/Mac does not use the native popups/menubar #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_cursorKeys2() { @@ -676,7 +682,7 @@ void tst_QMenuBar::check_cursorKeys2() /*! If a popupmenu is active you can use Left to move to the menu to the left of it. */ -// Qt/Mac,WinCE does not use the native popups/menubar +// Qt/Mac does not use the native popups/menubar #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_cursorKeys3() { @@ -791,7 +797,7 @@ void tst_QMenuBar::check_endKey() If Down is pressed next the popup is activated again. */ -// Qt/Mac,WinCE does not use the native popups/menubar +// Qt/Mac does not use the native popups/menubar #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_escKey() { @@ -1025,7 +1031,7 @@ void tst_QMenuBar::check_altClosePress() QTRY_VERIFY(!w.menuBar()->activeAction()); } -// Qt/Mac,WinCE does not use the native popups/menubar +// Qt/Mac does not use the native popups/menubar #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_shortcutPress() { @@ -1068,7 +1074,7 @@ private: const Qt::LayoutDirection m_oldDirection; }; -// Qt/Mac,WinCE does not use the native popups/menubar +// Qt/Mac does not use the native popups/menubar #if !defined(Q_OS_DARWIN) void tst_QMenuBar::check_menuPosition() { @@ -1530,6 +1536,41 @@ void tst_QMenuBar::slotForTaskQTBUG53205() taskQTBUG53205MenuBar->setParent(parent); } +// Qt/Mac does not use the native popups/menubar +#if !defined(Q_OS_DARWIN) +void tst_QMenuBar::taskQTBUG46812_doNotLeaveMenubarHighlighted() +{ + QMainWindow mainWindow; + QWidget *centralWidget = new QWidget; + centralWidget->setFocusPolicy(Qt::StrongFocus); + mainWindow.setCentralWidget(centralWidget); + initWindowWithSimpleMenuBar(mainWindow); + + mainWindow.show(); + QApplication::setActiveWindow(&mainWindow); + QVERIFY(QTest::qWaitForWindowActive(&mainWindow)); + + QVERIFY(!mainWindow.menuBar()->hasFocus()); + QCOMPARE(m_simpleActivatedCount, 0); + + QTest::keyPress(&mainWindow, Qt::Key_Alt, Qt::AltModifier); + QVERIFY(!mainWindow.menuBar()->hasFocus()); + QCOMPARE(m_simpleActivatedCount, 0); + + QTest::keyPress(&mainWindow, Qt::Key_Z, Qt::AltModifier); + QVERIFY(!mainWindow.menuBar()->hasFocus()); + QCOMPARE(m_simpleActivatedCount, 2); // the action AND the menu will activate + + QTest::keyRelease(&mainWindow, Qt::Key_Alt, Qt::NoModifier); + QVERIFY(!mainWindow.menuBar()->hasFocus()); + QCOMPARE(m_simpleActivatedCount, 2); + + QTest::keyRelease(&mainWindow, Qt::Key_Z, Qt::NoModifier); + QVERIFY(!mainWindow.menuBar()->hasFocus()); + QCOMPARE(m_simpleActivatedCount, 2); +} +#endif + #ifdef Q_OS_MACOS extern bool tst_qmenubar_taskQTBUG56275(QMenuBar *); diff --git a/tests/auto/widgets/widgets/qsplitter/tst_qsplitter.cpp b/tests/auto/widgets/widgets/qsplitter/tst_qsplitter.cpp index f490446c8a..72e6ffdeb5 100644 --- a/tests/auto/widgets/widgets/qsplitter/tst_qsplitter.cpp +++ b/tests/auto/widgets/widgets/qsplitter/tst_qsplitter.cpp @@ -77,6 +77,11 @@ private slots: void rubberBandNotInSplitter(); void saveAndRestoreStateOfNotYetShownSplitter(); void saveAndRestoreHandleWidth(); + void replaceWidget_data(); + void replaceWidget(); + void replaceWidgetWithSplitterChild_data(); + void replaceWidgetWithSplitterChild(); + void handleMinimumWidth(); // task-specific tests below me: void task187373_addAbstractScrollAreas(); @@ -645,9 +650,200 @@ public: MyFriendlySplitter(QWidget *parent = 0) : QSplitter(parent) {} void setRubberBand(int pos) { QSplitter::setRubberBand(pos); } + void moveSplitter(int pos, int index) { QSplitter::moveSplitter(pos, index); } + friend class tst_QSplitter; }; +class EventCounterSpy : public QObject +{ +public: + EventCounterSpy(QWidget *parentWidget) : QObject(parentWidget) + { } + + bool eventFilter(QObject *watched, QEvent *event) override + { + // Watch for events in the parent widget and all its children + if (watched == parent() || watched->parent() == parent()) { + if (event->type() == QEvent::Resize) + resizeCount++; + else if (event->type() == QEvent::Paint) + paintCount++; + } + + return QObject::eventFilter(watched, event); + } + + int resizeCount = 0; + int paintCount = 0; +}; + +void tst_QSplitter::replaceWidget_data() +{ + QTest::addColumn<int>("index"); + QTest::addColumn<bool>("visible"); + QTest::addColumn<bool>("collapsed"); + + QTest::newRow("negative index") << -1 << true << false; + QTest::newRow("index too large") << 80 << true << false; + QTest::newRow("visible, not collapsed") << 3 << true << false; + QTest::newRow("visible, collapsed") << 3 << true << true; + QTest::newRow("not visible, not collapsed") << 3 << false << false; + QTest::newRow("not visible, collapsed") << 3 << false << true; +} + +void tst_QSplitter::replaceWidget() +{ + QFETCH(int, index); + QFETCH(bool, visible); + QFETCH(bool, collapsed); + + // Setup + MyFriendlySplitter sp; + const int count = 7; + for (int i = 0; i < count; i++) { + // We use labels instead of plain widgets to + // make it easier to fix eventual regressions. + QLabel *w = new QLabel(QString::asprintf("WIDGET #%d", i)); + sp.addWidget(w); + } + sp.setWindowTitle(QString::asprintf("index %d, visible %d, collapsed %d", index, visible, collapsed)); + sp.show(); + QVERIFY(QTest::qWaitForWindowExposed(&sp)); + + // Configure splitter + QWidget *oldWidget = sp.widget(index); + const QRect oldGeom = oldWidget ? oldWidget->geometry() : QRect(); + if (oldWidget) { + // Collapse first, then hide, if necessary + if (collapsed) { + sp.setCollapsible(index, true); + sp.moveSplitter(oldWidget->x() + 1, index + 1); + } + if (!visible) + oldWidget->hide(); + } + + // Replace widget + QTest::qWait(100); // Flush event queue + const QList<int> sizes = sp.sizes(); + // Shorter label: The important thing is to ensure we can set + // the same size on the new widget. Because of QLabel's sizing + // constraints (they can expand but not shrink) the easiest is + // to set a shorter label. + QLabel *newWidget = new QLabel(QLatin1String("<b>NEW</b>")); + + EventCounterSpy *ef = new EventCounterSpy(&sp); + qApp->installEventFilter(ef); + const QWidget *res = sp.replaceWidget(index, newWidget); + QTest::qWait(100); // Give visibility and resizing some time + qApp->removeEventFilter(ef); + + // Check + if (index < 0 || index >= count) { + QVERIFY(!res); + QVERIFY(!newWidget->parentWidget()); + QCOMPARE(ef->resizeCount, 0); + QCOMPARE(ef->paintCount, 0); + } else { + QCOMPARE(res, oldWidget); + QVERIFY(!res->parentWidget()); + QVERIFY(!res->isVisible()); + QCOMPARE(newWidget->parentWidget(), &sp); + QCOMPARE(newWidget->isVisible(), visible); + if (visible && !collapsed) + QCOMPARE(newWidget->geometry(), oldGeom); + QCOMPARE(newWidget->size().isEmpty(), !visible || collapsed); + const int expectedResizeCount = visible ? 1 : 0; // new widget only + const int expectedPaintCount = visible && !collapsed ? 2 : 0; // splitter and new widget + QCOMPARE(ef->resizeCount, expectedResizeCount); + QCOMPARE(ef->paintCount, expectedPaintCount); + delete res; + } + QCOMPARE(sp.count(), count); + QCOMPARE(sp.sizes(), sizes); +} + +void tst_QSplitter::replaceWidgetWithSplitterChild_data() +{ + QTest::addColumn<int>("srcIndex"); + QTest::addColumn<int>("dstIndex"); + + QTest::newRow("replace with null widget") << -2 << 3; + QTest::newRow("replace with itself") << 3 << 3; + QTest::newRow("replace with sibling, after recalc") << 1 << 4; + QTest::newRow("replace with sibling, before recalc") << -1 << 4; +} + +void tst_QSplitter::replaceWidgetWithSplitterChild() +{ + QFETCH(int, srcIndex); + QFETCH(int, dstIndex); + + // Setup + MyFriendlySplitter sp; + const int count = 7; + for (int i = 0; i < count; i++) { + // We use labels instead of plain widgets to + // make it easier to fix eventual regressions. + QLabel *w = new QLabel(QString::asprintf("WIDGET #%d", i)); + sp.addWidget(w); + } + sp.setWindowTitle(QLatin1String(QTest::currentTestFunction()) + QLatin1Char(' ') + QLatin1String(QTest::currentDataTag())); + sp.show(); + QVERIFY(QTest::qWaitForWindowExposed(&sp)); + + QTest::qWait(100); // Flush event queue before new widget creation + const QList<int> sizes = sp.sizes(); + QWidget *sibling = srcIndex == -1 ? (new QLabel("<b>NEW</b>", &sp)) : sp.widget(srcIndex); + + EventCounterSpy *ef = new EventCounterSpy(&sp); + qApp->installEventFilter(ef); + const QWidget *res = sp.replaceWidget(dstIndex, sibling); + QTest::qWait(100); // Give visibility and resizing some time + qApp->removeEventFilter(ef); + + QVERIFY(!res); + if (srcIndex == -1) { + // Create and replace before recalc. The sibling is scheduled to be + // added after replaceWidget(), when QSplitter receives a child event. + QVERIFY(ef->resizeCount > 0); + QVERIFY(ef->paintCount > 0); + QCOMPARE(sp.count(), count + 1); + QCOMPARE(sp.sizes().mid(0, count), sizes); + QCOMPARE(sp.sizes().last(), sibling->width()); + } else { + // No-op for the rest + QCOMPARE(ef->resizeCount, 0); + QCOMPARE(ef->paintCount, 0); + QCOMPARE(sp.count(), count); + QCOMPARE(sp.sizes(), sizes); + } +} + +void tst_QSplitter::handleMinimumWidth() +{ + MyFriendlySplitter split; + split.addWidget(new QLabel("Number Wan")); + split.addWidget(new QLabel("Number Too")); + + split.show(); + QTest::qWaitForWindowExposed(&split); + for (int i = 0; i < 10; i++) { + split.setHandleWidth(i); + QTest::qWait(100); // resizing + QCOMPARE(split.handle(1)->width(), qMax(4 + (i & 1), i)); + } + + split.setOrientation(Qt::Vertical); + QTest::qWait(100); + for (int i = 0; i < 10; i++) { + split.setHandleWidth(i); + QTest::qWait(100); // resizing + QCOMPARE(split.handle(1)->height(), qMax(4 + (i & 1), i)); + } +} + void tst_QSplitter::rubberBandNotInSplitter() { MyFriendlySplitter split; |