void tst_qquickanimatedsprite::test_runningChangedSignal()
{
    QQuickView *window = new QQuickView(0);

    window->setSource(testFileUrl("runningChange.qml"));
    window->show();
    QVERIFY(QTest::qWaitForWindowExposed(window));

    QVERIFY(window->rootObject());
    QQuickAnimatedSprite* sprite = window->rootObject()->findChild<QQuickAnimatedSprite*>("sprite");
    QVERIFY(sprite);

    QVERIFY(!sprite->running());

    QSignalSpy runningChangedSpy(sprite, SIGNAL(runningChanged(bool)));
    sprite->setRunning(true);
    QTRY_COMPARE(runningChangedSpy.count(), 1);
    QTRY_VERIFY(!sprite->running());
    QTRY_COMPARE(runningChangedSpy.count(), 2);

    delete window;
}
Example #2
0
void tst_QNearFieldManager::registerNdefMessageHandler()
{
    QNearFieldManagerPrivateImpl *emulatorBackend = new QNearFieldManagerPrivateImpl;
    QNearFieldManager manager(emulatorBackend, 0);

    MessageListener listener;
    QSignalSpy messageSpy(&listener, SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));

    int id = manager.registerNdefMessageHandler(&listener,
                                                SIGNAL(matchedNdefMessage(QNdefMessage,QNearFieldTarget*)));

    QVERIFY(id != -1);

    QTRY_VERIFY(!messageSpy.isEmpty());

    const QNdefMessage message = messageSpy.first().at(0).value<QNdefMessage>();
    QNearFieldTarget *target = messageSpy.first().at(1).value<QNearFieldTarget *>();

    QVERIFY(target);

    QVERIFY(manager.unregisterNdefMessageHandler(id));
}
Example #3
0
void tst_QColumnView::selectedColumns()
{
    ColumnView view;
    QDirModel model;
    view.setModel(&model);
    view.resize(800,300);
    view.show();

    QModelIndex home = model.index(QDir::homePath());
    view.setCurrentIndex(home);

    QTest::qWait(ANIMATION_DELAY);

    for (int i = 0; i < view.createdColumns.count(); ++i) {
        QAbstractItemView *column = view.createdColumns.at(i);
        if (!column)
            continue;
        if (!column->rootIndex().isValid() || column->rootIndex() == home)
            continue;
        QTRY_VERIFY(column->currentIndex().isValid());
    }
}
Example #4
0
void TestSimPlugin::testClear()
{
    QContactManager &m(m_controller->contactManager());

    // Add two contacts manually
    QContact gump;

    QContactNickname n;
    n.setNickname("Forrest Gump");
    gump.saveDetail(&n);

    QContactSyncTarget st;
    st.setSyncTarget(QStringLiteral("sim-test"));
    gump.saveDetail(&st);

    QContact whittaker;

    n.setNickname("Forrest Whittaker");
    whittaker.saveDetail(&n);

    st.setSyncTarget(QStringLiteral("sim-test"));
    whittaker.saveDetail(&st);

    QVERIFY(m.saveContact(&gump));
    QVERIFY(m.saveContact(&whittaker));

    QCOMPARE(getAllSimContacts(m).count(), 2);
    QCOMPARE(m_controller->busy(), false);

    m_controller->simPresenceChanged(true);

    // Report the SIM card removed
    m_controller->simPresenceChanged(false);
    QTRY_VERIFY(m_controller->busy() == false);

    // All sim contacts should be removed
    QList<QContact> simContacts(getAllSimContacts(m));
    QCOMPARE(simContacts.count(), 0);
}
Example #5
0
// public void addWebAction(QAction* action, QWebPage::WebAction webAction)
void tst_TabWidget::addWebAction()
{
    QFETCH(QWebPage::WebAction, webAction);

    SubTabWidget widget;

    QSignalSpy spy0(&widget, SIGNAL(linkHovered(const QString &)));
    QSignalSpy spy1(&widget, SIGNAL(loadPage(const QString &)));
    QSignalSpy spy2(&widget, SIGNAL(loadProgress(int)));
    QSignalSpy spy3(&widget, SIGNAL(setCurrentTitle(const QString &)));
    QSignalSpy spy4(&widget, SIGNAL(showStatusBarMessage(const QString &)));
    QSignalSpy spy5(&widget, SIGNAL(tabsChanged()));
    QSignalSpy spy6(&widget, SIGNAL(lastTabClosed()));

    QAction *action = new QAction(&widget);
    widget.addWebAction(action, webAction);

    widget.newTab();
    QVERIFY(!action->isEnabled());

    widget.loadUrl(QUrl("about:config"));
    QUrl url1(":/notfound.html"); //QUrl("http://www.google.com/"));
    QUrl url2(":/notfound2.html"); //QUrl("http://www.yahoo.com/"));
    widget.loadUrl(url1);
    widget.loadUrl(url2);

    QTRY_VERIFY(action->isEnabled());
    widget.newTab();
    QVERIFY(!action->isEnabled());

    QCOMPARE(spy0.count(), 0);
    QCOMPARE(spy1.count(), 0);
    QVERIFY(spy2.count() > 0);
    QCOMPARE(spy3.count(), 8);
    QVERIFY(spy4.count() > 0);
    QCOMPARE(spy5.count(), 6);
    QCOMPARE(spy6.count(), 0);
}
void tst_qquickanimatedsprite::test_frameChangedSignal()
{
    QQuickView *window = new QQuickView(0);

    window->setSource(testFileUrl("frameChange.qml"));
    window->show();
    QVERIFY(QTest::qWaitForWindowExposed(window));

    QVERIFY(window->rootObject());
    QQuickAnimatedSprite* sprite = window->rootObject()->findChild<QQuickAnimatedSprite*>("sprite");
    QVERIFY(sprite);

    QVERIFY(!sprite->running());
    QVERIFY(!sprite->paused());
    QCOMPARE(sprite->loops(), 3);
    QCOMPARE(sprite->frameCount(), 6);

    QSignalSpy frameChangedSpy(sprite, SIGNAL(currentFrameChanged(int)));
    sprite->setRunning(true);
    QTRY_COMPARE(frameChangedSpy.count(), 3*6);
    QTRY_VERIFY(!sprite->running());

    delete window;
}
void tst_qquickanimatedsprite::test_properties()
{
    QQuickView *window = new QQuickView(0);

    window->setSource(testFileUrl("basic.qml"));
    window->show();
    QVERIFY(QTest::qWaitForWindowExposed(window));

    QVERIFY(window->rootObject());
    QQuickAnimatedSprite* sprite = window->rootObject()->findChild<QQuickAnimatedSprite*>("sprite");
    QVERIFY(sprite);

    QTRY_VERIFY(sprite->running());
    QVERIFY(!sprite->paused());
    QVERIFY(sprite->interpolate());
    QCOMPARE(sprite->loops(), 30);

    sprite->setRunning(false);
    QVERIFY(!sprite->running());
    sprite->setInterpolate(false);
    QVERIFY(!sprite->interpolate());

    delete window;
}
void tst_QWindowContainer::testActivation()
{
    QWidget root;

    QWindow *window = new QWindow();
    QWidget *container = QWidget::createWindowContainer(window, &root);

    container->setGeometry(100, 100, 200, 100);
    root.setGeometry(100, 100, 400, 300);

    root.show();
    root.activateWindow();
    QVERIFY(QTest::qWaitForWindowExposed(&root));

    QVERIFY(QTest::qWaitForWindowActive(root.windowHandle()));
    QVERIFY(QGuiApplication::focusWindow() == root.windowHandle());

    // Verify that all states in the root widget indicate it is active
    QVERIFY(root.windowHandle()->isActive());
    QVERIFY(root.isActiveWindow());
    QCOMPARE(root.palette().currentColorGroup(), QPalette::Active);

    // Under KDE (ubuntu 12.10), we experience that doing two activateWindow in a row
    // does not work. The second gets ignored by the window manager, even though the
    // timestamp in the xcb connection is unique for both.
    if (QGuiApplication::platformName() == "xcb")
        QTest::qWait(100);

    window->requestActivate();
    QTRY_VERIFY(QGuiApplication::focusWindow() == window);

    // Verify that all states in the root widget still indicate it is active
    QVERIFY(root.windowHandle()->isActive());
    QVERIFY(root.isActiveWindow());
    QCOMPARE(root.palette().currentColorGroup(), QPalette::Active);
}
Example #9
0
void tst_QItemDelegate::QTBUG4435_keepSelectionOnCheck()
{
    QStandardItemModel model(3, 1);
    for (int i = 0; i < 3; ++i) {
        QStandardItem *item = new QStandardItem(QLatin1String("Item ") + QString::number(i));
        item->setCheckable(true);
        item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled);
        model.setItem(i, item);
    }
    QTableView view;
    view.setModel(&model);
    view.setItemDelegate(new TestItemDelegate);
    view.show();
    view.selectAll();
    QTest::qWaitForWindowShown(&view);
    QStyleOptionViewItem option;
    option.rect = view.visualRect(model.index(0, 0));
    const int checkMargin = qApp->style()->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, 0) + 1;
    QPoint pos = qApp->style()->subElementRect(QStyle::SE_ViewItemCheckIndicator, &option, 0).center()
                 + QPoint(checkMargin, 0);
    QTest::mouseClick(view.viewport(), Qt::LeftButton, Qt::ControlModifier, pos);
    QTRY_VERIFY(view.selectionModel()->isColumnSelected(0, QModelIndex()));
    QCOMPARE(model.item(0)->checkState(), Qt::Checked);
}
void tst_QPauseAnimationJob::multipleSequentialGroups()
{
    EnableConsistentTiming enabled;

    QParallelAnimationGroupJob group;
    group.setLoopCount(2);

    QSequentialAnimationGroupJob subgroup1;
    group.appendAnimation(&subgroup1);

    TestableGenericAnimation animation(300);
    subgroup1.appendAnimation(&animation);

    TestablePauseAnimation pause(200);
    subgroup1.appendAnimation(&pause);

    QSequentialAnimationGroupJob subgroup2;
    group.appendAnimation(&subgroup2);

    TestableGenericAnimation animation2(200);
    subgroup2.appendAnimation(&animation2);

    TestablePauseAnimation pause2(250);
    subgroup2.appendAnimation(&pause2);

    QSequentialAnimationGroupJob subgroup3;
    group.appendAnimation(&subgroup3);

    TestablePauseAnimation pause3(400);
    subgroup3.appendAnimation(&pause3);

    TestableGenericAnimation animation3(200);
    subgroup3.appendAnimation(&animation3);

    QSequentialAnimationGroupJob subgroup4;
    group.appendAnimation(&subgroup4);

    TestablePauseAnimation pause4(310);
    subgroup4.appendAnimation(&pause4);

    TestablePauseAnimation pause5(60);
    subgroup4.appendAnimation(&pause5);

    group.start();

    QVERIFY(group.state() == QAbstractAnimationJob::Running);
    QVERIFY(subgroup1.state() == QAbstractAnimationJob::Running);
    QVERIFY(subgroup2.state() == QAbstractAnimationJob::Running);
    QVERIFY(subgroup3.state() == QAbstractAnimationJob::Running);
    QVERIFY(subgroup4.state() == QAbstractAnimationJob::Running);

    // This is a pretty long animation so it tends to get rather out of sync
    // when using the consistent timer, so run for an extra half second for good
    // measure...
    QTest::qWait(group.totalDuration() + 500);

#ifdef Q_OS_WIN
    if (group.state() != QAbstractAnimationJob::Stopped)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QTRY_VERIFY(group.state() == QAbstractAnimationJob::Stopped);

#ifdef Q_OS_WIN
    if (subgroup1.state() != QAbstractAnimationJob::Stopped)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QVERIFY(subgroup1.state() == QAbstractAnimationJob::Stopped);

#ifdef Q_OS_WIN
    if (subgroup2.state() != QAbstractAnimationJob::Stopped)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QVERIFY(subgroup2.state() == QAbstractAnimationJob::Stopped);

#ifdef Q_OS_WIN
    if (subgroup3.state() != QAbstractAnimationJob::Stopped)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QVERIFY(subgroup3.state() == QAbstractAnimationJob::Stopped);

#ifdef Q_OS_WIN
    if (subgroup4.state() != QAbstractAnimationJob::Stopped)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QVERIFY(subgroup4.state() == QAbstractAnimationJob::Stopped);

#ifdef Q_OS_WIN
    if (pause5.m_updateCurrentTimeCount != 4)
        QEXPECT_FAIL("", winTimerError, Abort);
#endif
    QCOMPARE(pause5.m_updateCurrentTimeCount, 4);
}
void tst_QQmlEngineDebugService::initTestCase()
{
    qmlRegisterType<NonScriptProperty>("Test", 1, 0, "NonScriptPropertyElement");

    QTest::ignoreMessage(QtDebugMsg, "QML Debugger: Waiting for connection on port 3768...");
    m_engine = new QQmlEngine(this);

    QList<QByteArray> qml;
    qml << "import QtQuick 2.0\n"
           "import Test 1.0\n"
           "Item {"
                "id: root\n"
                "width: 10; height: 20; scale: blueRect.scale;"
                "Rectangle { id: blueRect; width: 500; height: 600; color: \"blue\"; }"
                "Text { font.bold: true; color: blueRect.color; }"
                "MouseArea {"
                    "onEntered: { console.log('hello') }"
                "}"
                "property variant varObj\n"
                "property variant varObjList: []\n"
                "property variant varObjMap\n"
                "property variant simpleVar: 10.05\n"
                "Component.onCompleted: {\n"
                    "varObj = blueRect;\n"
                    "var list = varObjList;\n"
                    "list[0] = blueRect;\n"
                    "varObjList = list;\n"
                    "var map = new Object;\n"
                    "map.rect = blueRect;\n"
                    "varObjMap = map;\n"
                "}\n"
                "NonScriptPropertyElement {\n"
                "}\n"
            "}";

    // add second component to test multiple root contexts
    qml << "import QtQuick 2.0\n"
            "Item {}";

    // and a third to test methods
    qml << "import QtQuick 2.0\n"
            "Item {"
                "function myMethodNoArgs() { return 3; }\n"
                "function myMethod(a) { return a + 9; }\n"
                "function myMethodIndirect() { myMethod(3); }\n"
            "}";

    // and a fourth to test states
    qml << "import QtQuick 2.0\n"
           "Rectangle {\n"
                "id:rootRect\n"
                "width:100\n"
                "states: [\n"
                    "State {\n"
                        "name:\"state1\"\n"
                        "PropertyChanges {\n"
                            "target:rootRect\n"
                            "width:200\n"
                        "}\n"
                    "}\n"
                "]\n"
                "transitions: [\n"
                    "Transition {\n"
                        "from:\"*\"\n"
                        "to:\"state1\"\n"
                        "PropertyAnimation {\n"
                            "target:rootRect\n"
                            "property:\"width\"\n"
                            "duration:100\n"
                        "}\n"
                    "}\n"
                "]\n"
           "}\n"
           ;

    for (int i=0; i<qml.count(); i++) {
        QQmlComponent component(m_engine);
        component.setData(qml[i], QUrl::fromLocalFile(""));
        QVERIFY(component.isReady());  // fails if bad syntax
        m_components << qobject_cast<QQuickItem*>(component.create());
    }
    m_rootItem = qobject_cast<QQuickItem*>(m_components.first());

    // add an extra context to test for multiple contexts
    QQmlContext *context = new QQmlContext(m_engine->rootContext(), this);
    context->setObjectName("tst_QQmlDebug_childContext");

    m_conn = new QQmlDebugConnection(this);
    m_conn->connectToHost("127.0.0.1", 3768);

    bool ok = m_conn->waitForConnected();
    QVERIFY(ok);
    QTRY_VERIFY(QQmlDebugService::hasDebuggingClient());
    m_dbg = new QQmlEngineDebugClient(m_conn);
    QTRY_VERIFY(m_dbg->state() == QQmlEngineDebugClient::Enabled);
}
Example #12
0
void TestSimPlugin::testTrimWhitespace()
{
    QContactManager &m(m_controller->contactManager());

    QCOMPARE(getAllSimContacts(m).count(), 0);
    QCOMPARE(m_controller->busy(), false);

    m_controller->simPresenceChanged(true);
    QCOMPARE(m_controller->busy(), false);

    // Add a contact with two numbers
    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump\n"
"TEL;TYPE=HOME,VOICE:(404) 555-1212\n"
"TEL;TYPE=WORK,VIDEO:(404) 555-6789\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    QList<QContact> simContacts(getAllSimContacts(m));
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).details<QContactPhoneNumber>().count(), 2);
    foreach (const QContactPhoneNumber &number, simContacts.at(0).details<QContactPhoneNumber>()) {
        if (number.number() == QStringLiteral("(404) 555-1212")) {
            QVERIFY(number.contexts().contains(QContactDetail::ContextHome));
            QVERIFY(number.subTypes().contains(QContactPhoneNumber::SubTypeVoice));
        } else {
            QCOMPARE(number.number(), QStringLiteral("(404) 555-6789"));
            QVERIFY(number.contexts().contains(QContactDetail::ContextWork));
            QVERIFY(number.subTypes().contains(QContactPhoneNumber::SubTypeVideo));
        }
    }

    QContactId existingId = simContacts.at(0).id();

    // Add another contact with identical + whitespace name, changed number
    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump \n"
"TEL;TYPE=HOME,VOICE:(404) 555-1212\n"
"TEL;TYPE=WORK,VIDEO:(404) 555-6888\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    // Verify that the contact was not recreated, but instead updated
    simContacts = getAllSimContacts(m);
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).id(), existingId);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).details<QContactPhoneNumber>().count(), 2);
    foreach (const QContactPhoneNumber &number, simContacts.at(0).details<QContactPhoneNumber>()) {
        if (number.number() == QStringLiteral("(404) 555-1212")) {
            QVERIFY(number.contexts().contains(QContactDetail::ContextHome));
            QVERIFY(number.subTypes().contains(QContactPhoneNumber::SubTypeVoice));
        } else {
            QCOMPARE(number.number(), QStringLiteral("(404) 555-6888"));
            QVERIFY(number.contexts().contains(QContactDetail::ContextWork));
            QVERIFY(number.subTypes().contains(QContactPhoneNumber::SubTypeVideo));
        }
    }
}
Example #13
0
void TestSimPlugin::testChangedNumber()
{
    QContactManager &m(m_controller->contactManager());

    QCOMPARE(getAllSimContacts(m).count(), 0);
    QCOMPARE(m_controller->busy(), false);

    m_controller->simPresenceChanged(true);
    QCOMPARE(m_controller->busy(), false);

    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump\n"
"TEL;TYPE=HOME,VOICE:(404) 555-1212\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    QList<QContact> simContacts(getAllSimContacts(m));
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).detail<QContactPhoneNumber>().number(), QStringLiteral("(404) 555-1212"));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().contexts().contains(QContactDetail::ContextHome));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().subTypes().contains(QContactPhoneNumber::SubTypeVoice));

    QContactId existingId = simContacts.at(0).id();

    // Change the number and verify that it is updated in the database, but the contact was not recreated
    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump\n"
"TEL;TYPE=WORK,VIDEO:(404) 555-6789\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    simContacts = getAllSimContacts(m);
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).id(), existingId);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).detail<QContactPhoneNumber>().number(), QStringLiteral("(404) 555-6789"));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().contexts().contains(QContactDetail::ContextWork));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().subTypes().contains(QContactPhoneNumber::SubTypeVideo));

    // Change the context and verify that it is updated in the database
    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump\n"
"TEL;TYPE=HOME,VIDEO:(404) 555-6789\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    simContacts = getAllSimContacts(m);
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).id(), existingId);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).detail<QContactPhoneNumber>().number(), QStringLiteral("(404) 555-6789"));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().contexts().contains(QContactDetail::ContextHome));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().subTypes().contains(QContactPhoneNumber::SubTypeVideo));

    // Change the subtype and verify that it is updated in the database
    m_controller->vcardDataAvailable(QStringLiteral(
"BEGIN:VCARD\n"
"VERSION:3.0\n"
"FN:Forrest Gump\n"
"TEL;TYPE=HOME,VOICE,CELL:(404) 555-6789\n"
"END:VCARD\n"));
    QCOMPARE(m_controller->busy(), true);
    QTRY_VERIFY(m_controller->busy() == false);

    simContacts = getAllSimContacts(m);
    QCOMPARE(simContacts.count(), 1);
    QCOMPARE(simContacts.at(0).id(), existingId);
    QCOMPARE(simContacts.at(0).detail<QContactNickname>().nickname(), QStringLiteral("Forrest Gump"));
    QCOMPARE(simContacts.at(0).detail<QContactPhoneNumber>().number(), QStringLiteral("(404) 555-6789"));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().contexts().contains(QContactDetail::ContextHome));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().subTypes().contains(QContactPhoneNumber::SubTypeVoice));
    QVERIFY(simContacts.at(0).detail<QContactPhoneNumber>().subTypes().contains(QContactPhoneNumber::SubTypeMobile));
}
Example #14
0
/*!
 Description: Unit test for NFC LLCP server sync(waitXXX) functions

 TestScenario: 1. Server will listen to a pre-defined URI
               2. Wait client to connect.
               3. Read message from client.
               4. Echo the same message back to client
               5. Wait client disconnect event.

 TestExpectedResults:
               1. The listen successfully set up.
               2. The message has be received from client.
               3. The echoed message has been sent to client.
               4. Connection disconnected and NO error signals emitted.
*/
void tst_QLlcpServer::newConnection_wait()
{
    QFETCH(QString, uri);
    QFETCH(QString, hint);

    QLlcpServer server;
    qDebug() << "Create QLlcpServer completed";
    qDebug() << "Start listening...";
    bool ret = server.listen(uri);
    QVERIFY(ret);
    qDebug() << "Listen() return ok";
    QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));

    QNfcTestUtil::ShowAutoMsg(hint, &connectionSpy, 1);

    QTRY_VERIFY(!connectionSpy.isEmpty());
    qDebug() << "try to call nextPendingConnection()";
    QLlcpSocket *socket = server.nextPendingConnection();
    QVERIFY(socket != NULL);

    QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError)));
    //Get data from client
    const int Timeout = 10 * 1000;

    quint16 blockSize = 0;
    QDataStream in(socket);
    in.setVersion(QDataStream::Qt_4_6);
    while (socket->bytesAvailable() < (int)sizeof(quint16)) {
        bool ret = socket->waitForReadyRead(Timeout);
        QVERIFY(ret);
    }

    in >> blockSize;
    qDebug()<<"Read blockSize from client: " << blockSize;
    while (socket ->bytesAvailable() < blockSize) {
        bool ret = socket->waitForReadyRead(Timeout);
        QVERIFY(ret);
    }
    QString echo;
    in >> echo;
    qDebug() << "Read data from client:" << echo;
    //Send data to client
    QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));

    QByteArray block;
    QDataStream out(&block, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << echo;
    qDebug()<<"Write echoed data back to client";
    out.device()->seek(0);
    out << (quint16)(block.size() - sizeof(quint16));

    qint64 val = socket->write(block);
    qDebug("Write() return value = %d", val);
    QVERIFY(val == 0);

    ret = socket->waitForBytesWritten(Timeout);
    QVERIFY(ret);

    QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
    qint64 written = countBytesWritten(bytesWrittenSpy);

    while (written < block.size())
    {
        QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
        bool ret = socket->waitForBytesWritten(Timeout);
        QVERIFY(ret);
        QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
        written += countBytesWritten(bytesWrittenSpy);
    }
    QVERIFY(written == block.size());
    //Now data has been sent,check the if existing error
    if (!errorSpy.isEmpty())
    {
        QLlcpSocket::SocketError error = errorSpy.first().at(0).value<QLlcpSocket::SocketError>();
        qDebug("QLlcpSocket::SocketError =%d", error);
    }
    QVERIFY(errorSpy.isEmpty());
    QTest::qWait(1500);//give some time to client to finish
    server.close();
}
void tst_QNmeaPositionInfoSource::startUpdates_withTimeout()
{
    QNmeaPositionInfoSource source(m_mode);
    QNmeaPositionInfoSourceProxyFactory factory;
    QNmeaPositionInfoSourceProxy *proxy = static_cast<QNmeaPositionInfoSourceProxy*>(factory.createProxy(&source));

    QSignalSpy spyUpdate(proxy->source(), SIGNAL(positionUpdated(QGeoPositionInfo)));
    QSignalSpy spyTimeout(proxy->source(), SIGNAL(updateTimeout()));

    proxy->source()->setUpdateInterval(1000);
    proxy->source()->startUpdates();

    QDateTime dt = QDateTime::currentDateTime().toUTC();

    if (m_mode == QNmeaPositionInfoSource::SimulationMode) {
        // the first sentence primes the simulation
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(10)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(1100)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addMSecs(2200)).toLatin1());
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(9)).toLatin1());

        QTime t;
        t.start();

        for (int j = 1; j < 4; ++j) {
            QTRY_COMPARE(spyUpdate.count(), j);
            QCOMPARE(spyTimeout.count(), 0);
            int time = t.elapsed();
            QVERIFY((time > j*1000 - 300) && (time < j*1000 + 300));
        }

        spyUpdate.clear();

        QTRY_VERIFY_WITH_TIMEOUT((spyUpdate.count() == 0) && (spyTimeout.count() == 1), 7500);
        spyTimeout.clear();

        QTRY_VERIFY_WITH_TIMEOUT((spyUpdate.count() == 1) && (spyTimeout.count() == 0), 7500);

    } else {
        // dt + 900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);

        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(1)).toLatin1());
        // dt + 1200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 1900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(2)).toLatin1());

        // dt + 2200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 2900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 0);
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(3)).toLatin1());

        // dt + 3200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();

        // dt + 6900
        QTRY_VERIFY(spyUpdate.count() == 0 && spyTimeout.count() == 1);
        spyTimeout.clear();
        proxy->feedBytes(QLocationTestUtils::createRmcSentence(dt.addSecs(7)).toLatin1());

        // dt + 7200
        QTRY_VERIFY(spyUpdate.count() == 1 && spyTimeout.count() == 0);
        spyUpdate.clear();
    }
}
Example #16
0
QT_END_NAMESPACE


void tst_QButtonGroup::arrowKeyNavigation()
{
    if (!qt_tab_all_widgets())
        QSKIP("This test requires full keyboard control to be enabled.");

    QDialog dlg(0);
    QHBoxLayout layout(&dlg);
    QGroupBox g1("1", &dlg);
    QHBoxLayout g1layout(&g1);
    QRadioButton bt1("Radio1", &g1);
    QPushButton pb("PB", &g1);
    QLineEdit le(&g1);
    QRadioButton bt2("Radio2", &g1);
    g1layout.addWidget(&bt1);
    g1layout.addWidget(&pb);
    g1layout.addWidget(&le);
    g1layout.addWidget(&bt2);

    // create a mixed button group with radion buttons and push
    // buttons. Not very useful, but it tests borderline cases wrt
    // focus handling.
    QButtonGroup bgrp1(&g1);
    bgrp1.addButton(&bt1);
    bgrp1.addButton(&pb);
    bgrp1.addButton(&bt2);

    QGroupBox g2("2", &dlg);
    QVBoxLayout g2layout(&g2);
    // we don't need a button group here, because radio buttons are
    // auto exclusive, i.e. they group themselves in he same parent
    // widget.
    QRadioButton bt3("Radio3", &g2);
    QRadioButton bt4("Radio4", &g2);
    g2layout.addWidget(&bt3);
    g2layout.addWidget(&bt4);

    layout.addWidget(&g1);
    layout.addWidget(&g2);

    dlg.show();
    qApp->setActiveWindow(&dlg);
    QVERIFY(QTest::qWaitForWindowActive(&dlg));

    bt1.setFocus();

    QTRY_VERIFY(bt1.hasFocus());

    QTest::keyClick(&bt1, Qt::Key_Right);
    QVERIFY(pb.hasFocus());
    QTest::keyClick(&pb, Qt::Key_Right);
    QVERIFY(bt2.hasFocus());
    QTest::keyClick(&bt2, Qt::Key_Right);
    QVERIFY(bt2.hasFocus());
    QTest::keyClick(&bt2, Qt::Key_Left);
    QVERIFY(pb.hasFocus());
    QTest::keyClick(&pb, Qt::Key_Left);
    QVERIFY(bt1.hasFocus());

    QTest::keyClick(&bt1, Qt::Key_Tab);
    QVERIFY(pb.hasFocus());
    QTest::keyClick(&pb, Qt::Key_Tab);

    QVERIFY(le.hasFocus());
    QCOMPARE(le.selectedText(), le.text());
    QTest::keyClick(&le, Qt::Key_Tab);

    QVERIFY(bt2.hasFocus());
    QTest::keyClick(&bt2, Qt::Key_Tab);
    QVERIFY(bt3.hasFocus());

    QTest::keyClick(&bt3, Qt::Key_Down);
    QVERIFY(bt4.hasFocus());
    QTest::keyClick(&bt4, Qt::Key_Down);
    QVERIFY(bt4.hasFocus());

    QTest::keyClick(&bt4, Qt::Key_Up);
    QVERIFY(bt3.hasFocus());
    QTest::keyClick(&bt3, Qt::Key_Up);
    QVERIFY(bt3.hasFocus());
}
Example #17
0
/*!
 Description: Add a llcp2 server which will always
 run( actually run twice ), then a client in a device connect,
 after the case finish, another device connect the
 server again.

 CounterPart: tst_qllcpsockettype2 echo:"0"
 run this case twice to test multiConnection()
*/
void tst_QLlcpServer::multiConnection()
{
    QString uri = TestUri;
    QString hint ="multiConnection test";

    QLlcpServer server;
    qDebug() << "Create QLlcpServer completed";
    qDebug() << "Start listening...";
    QSignalSpy connectionSpy(&server, SIGNAL(newConnection()));

    bool ret = server.listen(uri);
    QVERIFY(ret);
    qDebug() << "Listen() return ok";
    const int KLoopCount = 2;
    int loopCount = 0;
    while(loopCount < KLoopCount)
    {
        qDebug() << "#########Loop count = " << loopCount <<" #########";
        QNfcTestUtil::ShowAutoMsg(hint, &connectionSpy, 1);

        QTRY_VERIFY(!connectionSpy.isEmpty());
        qDebug() << "try to call nextPendingConnection()";
        QLlcpSocket *socket = server.nextPendingConnection();
        QVERIFY(socket != NULL);
        QSignalSpy readyReadSpy(socket, SIGNAL(readyRead()));
        QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketError)));

        //Get data from client
        QTRY_VERIFY(!readyReadSpy.isEmpty());

        qDebug() << "Bytes available = " << socket->bytesAvailable();
        quint16 blockSize = 0;
        QDataStream in(socket);
        in.setVersion(QDataStream::Qt_4_6);
        while (socket->bytesAvailable() < (int)sizeof(quint16)) {
            QSignalSpy readyRead(socket, SIGNAL(readyRead()));
            QTRY_VERIFY(!readyRead.isEmpty());
        }
        in >> blockSize;
        qDebug()<<"Read blockSize from client: " << blockSize;
        while (socket ->bytesAvailable() < blockSize) {
            QSignalSpy readyRead(socket, SIGNAL(readyRead()));
            QTRY_VERIFY(!readyRead.isEmpty());
        }
        QString echo;
        in >> echo;
        qDebug() << "Read data from client:" << echo;
        //Send data to client
        QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
        QByteArray block;
        QDataStream out(&block, QIODevice::WriteOnly);
        out.setVersion(QDataStream::Qt_4_6);
        out << (quint16)0;
        out << echo;
        qDebug()<<"Write echoed data back to client";
        out.device()->seek(0);
        out << (quint16)(block.size() - sizeof(quint16));
        qint64 val = socket->write(block);
        qDebug("Write() return value = %d", val);
        QVERIFY(val == 0);

        QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
        qint64 written = countBytesWritten(bytesWrittenSpy);
        qDebug()<<"Server::bytesWritten signal return value = " << written;
        while (written < block.size())
        {
            QSignalSpy bytesWrittenSpy(socket, SIGNAL(bytesWritten(qint64)));
            QTRY_VERIFY(!bytesWrittenSpy.isEmpty());
            written += countBytesWritten(bytesWrittenSpy);
        }
        QVERIFY(written == block.size());
        //Now data has been sent,check the if existing error
        QVERIFY(errorSpy.isEmpty());

        connectionSpy.removeFirst();
        loopCount++;
    }
    QTest::qWait(1500);//give some time to client to finish
    server.close();
}
void QmlProfilerToolTest::testAttachToWaitingApplication()
{
    auto newKit = std::make_unique<ProjectExplorer::Kit>("fookit");
    ProjectExplorer::Kit * newKitPtr = newKit.get();
    ProjectExplorer::KitManager *kitManager = ProjectExplorer::KitManager::instance();
    QVERIFY(kitManager);
    QVERIFY(kitManager->registerKit(std::move(newKit)));
    QSettings *settings = Core::ICore::settings();
    QVERIFY(settings);
    settings->setValue(QLatin1String("AnalyzerQmlAttachDialog/kitId"), newKitPtr->id().toSetting());

    QmlProfilerTool profilerTool;

    QmlProfilerClientManager *clientManager = profilerTool.clientManager();
    clientManager->setRetryInterval(10);
    clientManager->setMaximumRetries(10);
    connect(clientManager, &QmlProfilerClientManager::connectionFailed,
            clientManager, &QmlProfilerClientManager::retryConnect);

    QTcpServer server;
    QUrl serverUrl = Utils::urlFromLocalHostAndFreePort();
    QVERIFY(serverUrl.port() >= 0);
    QVERIFY(serverUrl.port() <= std::numeric_limits<quint16>::max());
    server.listen(QHostAddress::Any, static_cast<quint16>(serverUrl.port()));

    QScopedPointer<QTcpSocket> connection;
    connect(&server, &QTcpServer::newConnection, this, [&]() {
        connection.reset(server.nextPendingConnection());
        fakeDebugServer(connection.data());
    });

    QTimer timer;
    timer.setInterval(100);

    bool modalSeen = false;
    connect(&timer, &QTimer::timeout, this, [&]() {
        if (QWidget *activeModal = QApplication::activeModalWidget()) {
            modalSeen = true;
            auto dialog = qobject_cast<QmlProfilerAttachDialog *>(activeModal);
            if (dialog) {
                dialog->setPort(serverUrl.port());
                dialog->accept();
                timer.stop();
            } else {
                qWarning() << "Some other modal widget popped up:" << activeModal;
                activeModal->close();
            }
        }
    });

    timer.start();
    ProjectExplorer::RunControl *runControl = profilerTool.attachToWaitingApplication();
    QVERIFY(runControl);

    QTRY_VERIFY(connection);
    QTRY_VERIFY(runControl->isRunning());
    QTRY_VERIFY(modalSeen);
    QTRY_VERIFY(!timer.isActive());
    QTRY_VERIFY(clientManager->isConnected());

    connection.reset();
    QTRY_VERIFY(runControl->isStopped());
}
Example #19
0
 void waitForLoad()
 {
     QTRY_VERIFY(status() == QQmlComponent::Ready || status() == QQmlComponent::Error);
 }
Example #20
0
void TestGui::testSearch()
{
    QAction* searchAction = m_mainWindow->findChild<QAction*>("actionSearch");
    QVERIFY(searchAction->isEnabled());
    QToolBar* toolBar = m_mainWindow->findChild<QToolBar*>("toolBar");
    QWidget* searchActionWidget = toolBar->widgetForAction(searchAction);
    EntryView* entryView = m_dbWidget->findChild<EntryView*>("entryView");
    QLineEdit* searchEdit = m_dbWidget->findChild<QLineEdit*>("searchEdit");
    QToolButton* clearSearch = m_dbWidget->findChild<QToolButton*>("clearButton");

    QVERIFY(!searchEdit->hasFocus());

    // Enter search
    QTest::mouseClick(searchActionWidget, Qt::LeftButton);
    QTRY_VERIFY(searchEdit->hasFocus());
    // Search for "ZZZ"
    QTest::keyClicks(searchEdit, "ZZZ");
    QTRY_COMPARE(entryView->model()->rowCount(), 0);
    // Escape
    QTest::keyClick(m_mainWindow, Qt::Key_Escape);
    QTRY_VERIFY(!searchEdit->hasFocus());
    // Enter search again
    QTest::mouseClick(searchActionWidget, Qt::LeftButton);
    QTRY_VERIFY(searchEdit->hasFocus());
    // Input and clear
    QTest::keyClicks(searchEdit, "ZZZ");
    QTRY_COMPARE(searchEdit->text(), QString("ZZZ"));
    QTest::mouseClick(clearSearch, Qt::LeftButton);
    QTRY_COMPARE(searchEdit->text(), QString(""));
    // Triggering search should select the existing text
    QTest::keyClicks(searchEdit, "ZZZ");
    QTest::mouseClick(searchActionWidget, Qt::LeftButton);
    QTRY_VERIFY(searchEdit->hasFocus());
    // Search for "some"
    QTest::keyClicks(searchEdit, "some");
    QTRY_COMPARE(entryView->model()->rowCount(), 4);

    clickIndex(entryView->model()->index(0, 1), entryView, Qt::LeftButton);
    QAction* entryEditAction = m_mainWindow->findChild<QAction*>("actionEntryEdit");
    QVERIFY(entryEditAction->isEnabled());
    QWidget* entryEditWidget = toolBar->widgetForAction(entryEditAction);
    QVERIFY(entryEditWidget->isVisible());
    QVERIFY(entryEditWidget->isEnabled());
    QTest::mouseClick(entryEditWidget, Qt::LeftButton);

    QCOMPARE(m_dbWidget->currentMode(), DatabaseWidget::EditMode);

    EditEntryWidget* editEntryWidget = m_dbWidget->findChild<EditEntryWidget*>("editEntryWidget");
    QDialogButtonBox* editEntryWidgetButtonBox = editEntryWidget->findChild<QDialogButtonBox*>("buttonBox");
    QTest::mouseClick(editEntryWidgetButtonBox->button(QDialogButtonBox::Ok), Qt::LeftButton);

    QCOMPARE(m_dbWidget->currentMode(), DatabaseWidget::ViewMode);

    clickIndex(entryView->model()->index(1, 0), entryView, Qt::LeftButton);
    QAction* entryDeleteAction = m_mainWindow->findChild<QAction*>("actionEntryDelete");

    QWidget* entryDeleteWidget = toolBar->widgetForAction(entryDeleteAction);
    QVERIFY(entryDeleteWidget->isVisible());
    QVERIFY(entryDeleteWidget->isEnabled());
    QVERIFY(!m_db->metadata()->recycleBin());

    QTest::mouseClick(entryDeleteWidget, Qt::LeftButton);

    QCOMPARE(entryView->model()->rowCount(), 3);
    QCOMPARE(m_db->metadata()->recycleBin()->entries().size(), 1);

    clickIndex(entryView->model()->index(1, 0), entryView, Qt::LeftButton);
    clickIndex(entryView->model()->index(2, 0), entryView, Qt::LeftButton, Qt::ControlModifier);
    QCOMPARE(entryView->selectionModel()->selectedRows().size(), 2);

    MessageBox::setNextAnswer(QMessageBox::No);
    QTest::mouseClick(entryDeleteWidget, Qt::LeftButton);
    QCOMPARE(entryView->model()->rowCount(), 3);
    QCOMPARE(m_db->metadata()->recycleBin()->entries().size(), 1);

    MessageBox::setNextAnswer(QMessageBox::Yes);
    QTest::mouseClick(entryDeleteWidget, Qt::LeftButton);
    QCOMPARE(entryView->model()->rowCount(), 1);
    QCOMPARE(m_db->metadata()->recycleBin()->entries().size(), 3);

    QWidget* closeSearchButton = m_dbWidget->findChild<QToolButton*>("closeSearchButton");
    QTest::mouseClick(closeSearchButton, Qt::LeftButton);

    QCOMPARE(entryView->model()->rowCount(), 1);
}
Example #21
0
void tst_QColumnView::scrollTo()
{
    QFETCH(bool, reverse);
    QFETCH(bool, giveFocus);
    if (reverse)
        qApp->setLayoutDirection(Qt::RightToLeft);
    ColumnView view;
    view.resize(200, 200);
    view.show();
    view.scrollTo(QModelIndex(), QAbstractItemView::EnsureVisible);
    QCOMPARE(view.HorizontalOffset(), 0);

    TreeModel model;
    view.setModel(&model);
    view.scrollTo(QModelIndex(), QAbstractItemView::EnsureVisible);

    QModelIndex home;
    home = model.index(0, 0, home);
    home = model.index(0, 0, home);
    home = model.index(0, 0, home);
    view.scrollTo(home, QAbstractItemView::EnsureVisible);
    QModelIndex homeFile = model.index(0, 0, home);
    view.setRootIndex(home);

    QModelIndex index = model.index(0, 0, home);
    view.scrollTo(index, QAbstractItemView::EnsureVisible);
    QCOMPARE(view.HorizontalOffset(), 0);

    // Embedded requires that at least one widget have focus
    QWidget w;
    w.show();

    if (giveFocus)
        view.setFocus(Qt::OtherFocusReason);
    else
        view.clearFocus();
    QTRY_COMPARE(view.hasFocus(), giveFocus);
    // scroll to the right
    int level = 0;
    int last = view.HorizontalOffset();
    while(model.hasChildren(index) && level < 5) {
        view.setCurrentIndex(index);
        QTest::qWait(ANIMATION_DELAY);
        view.scrollTo(index, QAbstractItemView::EnsureVisible);
        QTest::qWait(ANIMATION_DELAY);
        qApp->processEvents();
        index = model.index(0, 0, index);
        level++;
        if (level >= 2) {
            if (!reverse) {
                QTRY_VERIFY(view.HorizontalOffset() < 0);
                QTRY_VERIFY(last > view.HorizontalOffset());
            } else {
                QTRY_VERIFY(view.HorizontalOffset() > 0);
                QTRY_VERIFY(last < view.HorizontalOffset());
            }
        }
        last = view.HorizontalOffset();
    }

    // scroll to the left
    int start = level;
    while(index.parent().isValid() && index != view.rootIndex()) {
        view.setCurrentIndex(index);
        QTest::qWait(ANIMATION_DELAY);
        view.scrollTo(index, QAbstractItemView::EnsureVisible);
        index = index.parent();
        if (start != level) {
            if (!reverse)
                QTRY_VERIFY(last < view.HorizontalOffset());
            else
                QTRY_VERIFY(last > view.HorizontalOffset());
        }
        level--;
        last = view.HorizontalOffset();
    }
    // It shouldn't automatically steal focus if it doesn't have it
    QTRY_COMPARE(view.hasFocus(), giveFocus);

    // Try scrolling to something that is above the root index
    home = model.index(0, 0, QModelIndex());
    QModelIndex temp = model.index(1, 0, home);
    home = model.index(0, 0, home);
    home = model.index(0, 0, home);
    view.setRootIndex(home);
    view.scrollTo(model.index(0, 0, home));
    QTest::qWait(ANIMATION_DELAY);
    view.scrollTo(temp);
}
/*
 The corrupted file is generated by copying a few random numbers
 from /dev/random on a linux machine.
*/
void tst_QAudioDecoderBackend::corruptedFileTest()
{
    QAudioDecoder d;
    QAudioBuffer buffer;

    QVERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(d.bufferAvailable() == false);
    QCOMPARE(d.sourceFilename(), QString(""));
    QVERIFY(d.audioFormat() == QAudioFormat());

    // Test local file
    QFileInfo fileInfo(QFINDTESTDATA(TEST_CORRUPTED_FILE_NAME));
    d.setSourceFilename(fileInfo.absoluteFilePath());
    QVERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(!d.bufferAvailable());
    QCOMPARE(d.sourceFilename(), fileInfo.absoluteFilePath());

    QSignalSpy readySpy(&d, SIGNAL(bufferReady()));
    QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool)));
    QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error)));
    QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State)));
    QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64)));
    QSignalSpy finishedSpy(&d, SIGNAL(finished()));
    QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64)));

    d.start();
    QTRY_VERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(!d.bufferAvailable());
    QCOMPARE(d.audioFormat(), QAudioFormat());
    QCOMPARE(d.duration(), qint64(-1));
    QCOMPARE(d.position(), qint64(-1));

    // Check the error code.
    QTRY_VERIFY(!errorSpy.isEmpty());

    // Have to use qvariant_cast, toInt will return 0 because unrecognized type;
    QAudioDecoder::Error errorCode = qvariant_cast<QAudioDecoder::Error>(errorSpy.takeLast().at(0));
    QCOMPARE(errorCode, QAudioDecoder::FormatError);
    QCOMPARE(d.error(), QAudioDecoder::FormatError);

    // Check all other spies.
    QVERIFY(readySpy.isEmpty());
    QVERIFY(bufferChangedSpy.isEmpty());
    QVERIFY(stateSpy.isEmpty());
    QVERIFY(finishedSpy.isEmpty());
    QVERIFY(positionSpy.isEmpty());
    QVERIFY(durationSpy.isEmpty());

    errorSpy.clear();

    // Try read even if the file is corrupted to test the robustness.
    buffer = d.read();
    QTRY_VERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(!buffer.isValid());
    QVERIFY(!d.bufferAvailable());
    QCOMPARE(d.position(), qint64(-1));

    QVERIFY(errorSpy.isEmpty());
    QVERIFY(readySpy.isEmpty());
    QVERIFY(bufferChangedSpy.isEmpty());
    QVERIFY(stateSpy.isEmpty());
    QVERIFY(finishedSpy.isEmpty());
    QVERIFY(positionSpy.isEmpty());
    QVERIFY(durationSpy.isEmpty());


    d.stop();
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);
    QCOMPARE(d.duration(), qint64(-1));
    QVERIFY(!d.bufferAvailable());
}
Example #23
0
/*
    Test running via QThreadPool::globalInstance()
*/
void tst_QThreadPool::singleton()
{
    ran = false;
    QThreadPool::globalInstance()->start(new TestTask());
    QTRY_VERIFY(ran);
}
void tst_QAudioDecoderBackend::fileTest()
{
    QAudioDecoder d;
    QAudioBuffer buffer;
    quint64 duration = 0;
    int byteCount = 0;
    int sampleCount = 0;

    QVERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(d.bufferAvailable() == false);
    QCOMPARE(d.sourceFilename(), QString(""));
    QVERIFY(d.audioFormat() == QAudioFormat());

    // Test local file
    QFileInfo fileInfo(QFINDTESTDATA(TEST_FILE_NAME));
    d.setSourceFilename(fileInfo.absoluteFilePath());
    QVERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(!d.bufferAvailable());
    QCOMPARE(d.sourceFilename(), fileInfo.absoluteFilePath());

    QSignalSpy readySpy(&d, SIGNAL(bufferReady()));
    QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool)));
    QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error)));
    QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State)));
    QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64)));
    QSignalSpy finishedSpy(&d, SIGNAL(finished()));
    QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64)));

    d.start();
    QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState);
    QTRY_VERIFY(!stateSpy.isEmpty());
    QTRY_VERIFY(!readySpy.isEmpty());
    QTRY_VERIFY(!bufferChangedSpy.isEmpty());
    QVERIFY(d.bufferAvailable());
    QTRY_VERIFY(!durationSpy.isEmpty());
    QVERIFY(qAbs(d.duration() - 1000) < 20);

    buffer = d.read();
    QVERIFY(buffer.isValid());

    // Test file is 44.1K 16bit mono, 44094 samples
    QCOMPARE(buffer.format().channelCount(), 1);
    QCOMPARE(buffer.format().sampleRate(), 44100);
    QCOMPARE(buffer.format().sampleSize(), 16);
    QCOMPARE(buffer.format().sampleType(), QAudioFormat::SignedInt);
    QCOMPARE(buffer.format().codec(), QString("audio/pcm"));
    QCOMPARE(buffer.byteCount(), buffer.sampleCount() * 2); // 16bit mono

    // The decoder should still have no format set
    QVERIFY(d.audioFormat() == QAudioFormat());

    QVERIFY(errorSpy.isEmpty());

    duration += buffer.duration();
    sampleCount += buffer.sampleCount();
    byteCount += buffer.byteCount();

    // Now drain the decoder
    if (sampleCount < 44094) {
        QTRY_COMPARE(d.bufferAvailable(), true);
    }

    while (d.bufferAvailable()) {
        buffer = d.read();
        QVERIFY(buffer.isValid());
        QTRY_VERIFY(!positionSpy.isEmpty());
        QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000));

        duration += buffer.duration();
        sampleCount += buffer.sampleCount();
        byteCount += buffer.byteCount();

        if (sampleCount < 44094) {
            QTRY_COMPARE(d.bufferAvailable(), true);
        }
    }

    // Make sure the duration is roughly correct (+/- 20ms)
    QCOMPARE(sampleCount, 44094);
    QCOMPARE(byteCount, 44094 * 2);
    QVERIFY(qAbs(qint64(duration) - 1000000) < 20000);
    QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20);
    QTRY_COMPARE(finishedSpy.count(), 1);
    QVERIFY(!d.bufferAvailable());
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);

    d.stop();
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);
    QTRY_COMPARE(durationSpy.count(), 2);
    QCOMPARE(d.duration(), qint64(-1));
    QVERIFY(!d.bufferAvailable());
    readySpy.clear();
    bufferChangedSpy.clear();
    stateSpy.clear();
    durationSpy.clear();
    finishedSpy.clear();
    positionSpy.clear();

    // change output audio format
    QAudioFormat format;
    format.setChannelCount(2);
    format.setSampleSize(8);
    format.setSampleRate(11050);
    format.setCodec("audio/pcm");
    format.setSampleType(QAudioFormat::SignedInt);

    d.setAudioFormat(format);

    // We expect 1 second still, at 11050 * 2 samples == 22k samples.
    // (at 1 byte/sample -> 22kb)

    // Make sure it stuck
    QVERIFY(d.audioFormat() == format);

    duration = 0;
    sampleCount = 0;
    byteCount = 0;

    d.start();
    QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState);
    QTRY_VERIFY(!stateSpy.isEmpty());
    QTRY_VERIFY(!readySpy.isEmpty());
    QTRY_VERIFY(!bufferChangedSpy.isEmpty());
    QVERIFY(d.bufferAvailable());
    QTRY_VERIFY(!durationSpy.isEmpty());
    QVERIFY(qAbs(d.duration() - 1000) < 20);

    buffer = d.read();
    QVERIFY(buffer.isValid());
    // See if we got the right format
    QVERIFY(buffer.format() == format);

    // The decoder should still have the same format
    QVERIFY(d.audioFormat() == format);

    QVERIFY(errorSpy.isEmpty());

    duration += buffer.duration();
    sampleCount += buffer.sampleCount();
    byteCount += buffer.byteCount();

    // Now drain the decoder
    if (duration < 998000) {
        QTRY_COMPARE(d.bufferAvailable(), true);
    }

    while (d.bufferAvailable()) {
        buffer = d.read();
        QVERIFY(buffer.isValid());
        QTRY_VERIFY(!positionSpy.isEmpty());
        QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000));
        QVERIFY(d.position() - (duration / 1000) < 20);

        duration += buffer.duration();
        sampleCount += buffer.sampleCount();
        byteCount += buffer.byteCount();

        if (duration < 998000) {
            QTRY_COMPARE(d.bufferAvailable(), true);
        }
    }

    // Resampling might end up with fewer or more samples
    // so be a bit sloppy
    QVERIFY(qAbs(sampleCount - 22047) < 100);
    QVERIFY(qAbs(byteCount - 22047) < 100);
    QVERIFY(qAbs(qint64(duration) - 1000000) < 20000);
    QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20);
    QTRY_COMPARE(finishedSpy.count(), 1);
    QVERIFY(!d.bufferAvailable());
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);

    d.stop();
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);
    QTRY_COMPARE(durationSpy.count(), 2);
    QCOMPARE(d.duration(), qint64(-1));
    QVERIFY(!d.bufferAvailable());
}
Example #25
0
void tst_QToolTip::cleanup()
{
    QTRY_VERIFY(QApplication::topLevelWidgets().isEmpty());
}
Example #26
0
 void cleanup()
 {
     // make sure the surfaces from the last test are properly cleaned up
     // and don't show up as false positives in the next test
     QTRY_VERIFY(!compositor->surface());
 }
void tst_QAudioDecoderBackend::deviceTest()
{
    QAudioDecoder d;
    QAudioBuffer buffer;
    quint64 duration = 0;
    int sampleCount = 0;

    QSignalSpy readySpy(&d, SIGNAL(bufferReady()));
    QSignalSpy bufferChangedSpy(&d, SIGNAL(bufferAvailableChanged(bool)));
    QSignalSpy errorSpy(&d, SIGNAL(error(QAudioDecoder::Error)));
    QSignalSpy stateSpy(&d, SIGNAL(stateChanged(QAudioDecoder::State)));
    QSignalSpy durationSpy(&d, SIGNAL(durationChanged(qint64)));
    QSignalSpy finishedSpy(&d, SIGNAL(finished()));
    QSignalSpy positionSpy(&d, SIGNAL(positionChanged(qint64)));

    QVERIFY(d.state() == QAudioDecoder::StoppedState);
    QVERIFY(d.bufferAvailable() == false);
    QCOMPARE(d.sourceFilename(), QString(""));
    QVERIFY(d.audioFormat() == QAudioFormat());

    QFileInfo fileInfo(QFINDTESTDATA(TEST_FILE_NAME));
    QFile file(fileInfo.absoluteFilePath());
    QVERIFY(file.open(QIODevice::ReadOnly));
    d.setSourceDevice(&file);

    QVERIFY(d.sourceDevice() == &file);
    QVERIFY(d.sourceFilename().isEmpty());

    // We haven't set the format yet
    QVERIFY(d.audioFormat() == QAudioFormat());

    d.start();
    QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState);
    QTRY_VERIFY(!stateSpy.isEmpty());
    QTRY_VERIFY(!readySpy.isEmpty());
    QTRY_VERIFY(!bufferChangedSpy.isEmpty());
    QVERIFY(d.bufferAvailable());
    QTRY_VERIFY(!durationSpy.isEmpty());
    QVERIFY(qAbs(d.duration() - 1000) < 20);

    buffer = d.read();
    QVERIFY(buffer.isValid());

    // Test file is 44.1K 16bit mono
    QCOMPARE(buffer.format().channelCount(), 1);
    QCOMPARE(buffer.format().sampleRate(), 44100);
    QCOMPARE(buffer.format().sampleSize(), 16);
    QCOMPARE(buffer.format().sampleType(), QAudioFormat::SignedInt);
    QCOMPARE(buffer.format().codec(), QString("audio/pcm"));

    QVERIFY(errorSpy.isEmpty());

    duration += buffer.duration();
    sampleCount += buffer.sampleCount();

    // Now drain the decoder
    if (sampleCount < 44094) {
        QTRY_COMPARE(d.bufferAvailable(), true);
    }

    while (d.bufferAvailable()) {
        buffer = d.read();
        QVERIFY(buffer.isValid());
        QTRY_VERIFY(!positionSpy.isEmpty());
        QVERIFY(positionSpy.takeLast().at(0).toLongLong() == qint64(duration / 1000));
        QVERIFY(d.position() - (duration / 1000) < 20);

        duration += buffer.duration();
        sampleCount += buffer.sampleCount();
        if (sampleCount < 44094) {
            QTRY_COMPARE(d.bufferAvailable(), true);
        }
    }

    // Make sure the duration is roughly correct (+/- 20ms)
    QCOMPARE(sampleCount, 44094);
    QVERIFY(qAbs(qint64(duration) - 1000000) < 20000);
    QVERIFY(qAbs((d.position() + (buffer.duration() / 1000)) - 1000) < 20);
    QTRY_COMPARE(finishedSpy.count(), 1);
    QVERIFY(!d.bufferAvailable());
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);

    d.stop();
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);
    QVERIFY(!d.bufferAvailable());
    QTRY_COMPARE(durationSpy.count(), 2);
    QCOMPARE(d.duration(), qint64(-1));
    readySpy.clear();
    bufferChangedSpy.clear();
    stateSpy.clear();
    durationSpy.clear();
    finishedSpy.clear();
    positionSpy.clear();

    // Now try changing formats
    QAudioFormat format;
    format.setChannelCount(2);
    format.setSampleSize(8);
    format.setSampleRate(8000);
    format.setCodec("audio/pcm");
    format.setSampleType(QAudioFormat::SignedInt);

    d.setAudioFormat(format);

    // Make sure it stuck
    QVERIFY(d.audioFormat() == format);

    d.start();
    QTRY_VERIFY(d.state() == QAudioDecoder::DecodingState);
    QTRY_VERIFY(!stateSpy.isEmpty());
    QTRY_VERIFY(!readySpy.isEmpty());
    QTRY_VERIFY(!bufferChangedSpy.isEmpty());
    QVERIFY(d.bufferAvailable());
    QTRY_VERIFY(!durationSpy.isEmpty());
    QVERIFY(qAbs(d.duration() - 1000) < 20);

    buffer = d.read();
    QVERIFY(buffer.isValid());
    // See if we got the right format
    QVERIFY(buffer.format() == format);

    // The decoder should still have the same format
    QVERIFY(d.audioFormat() == format);

    QVERIFY(errorSpy.isEmpty());

    d.stop();
    QTRY_COMPARE(d.state(), QAudioDecoder::StoppedState);
    QVERIFY(!d.bufferAvailable());
    QTRY_COMPARE(durationSpy.count(), 2);
    QCOMPARE(d.duration(), qint64(-1));
}
void LocalQmlProfilerRunnerTest::testRunner()
{
    QmlProfilerTool tool;
    QPointer<ProjectExplorer::RunControl> runControl;
    QPointer<LocalQmlProfilerSupport> profiler;
    ProjectExplorer::StandardRunnable debuggee;
    QUrl serverUrl;

    bool running = false;
    bool started = false;
    int startCount = 0;
    int runCount = 0;
    int stopCount = 0;

    debuggee.executable = "\\-/|\\-/";
    debuggee.environment = Utils::Environment::systemEnvironment();

    // should not be used anywhere but cannot be empty
    serverUrl.setScheme(Utils::urlSocketScheme());
    serverUrl.setPath("invalid");

    runControl = new ProjectExplorer::RunControl(nullptr,
                                                 ProjectExplorer::Constants::QML_PROFILER_RUN_MODE);
    runControl->setRunnable(debuggee);
    profiler = new LocalQmlProfilerSupport(&tool, runControl, serverUrl);

    auto connectRunner = [&]() {
        connect(runControl, &ProjectExplorer::RunControl::aboutToStart, this, [&]() {
            QVERIFY(!started);
            QVERIFY(!running);
            ++startCount;
            started = true;
        });
        connect(runControl, &ProjectExplorer::RunControl::started, this, [&]() {
            QVERIFY(started);
            QVERIFY(!running);
            ++runCount;
            running = true;
        });
        connect(runControl, &ProjectExplorer::RunControl::stopped, this, [&]() {
            QVERIFY(started);
            ++stopCount;
            running = false;
            started = false;
        });
        connect(runControl, &ProjectExplorer::RunControl::finished, this, [&]() {
            running = false;
            started = false;
        });
    };

    connectRunner();

    runControl->initiateStart();

    QTRY_COMPARE_WITH_TIMEOUT(startCount, 1, 30000);
    QTRY_VERIFY_WITH_TIMEOUT(!started, 30000);
    QCOMPARE(stopCount, 1);
    QCOMPARE(runCount, 0);

    runControl->initiateFinish();
    QTRY_VERIFY(runControl.isNull());
    QVERIFY(profiler.isNull());

    serverUrl = Utils::urlFromLocalSocket();
    debuggee.executable = qApp->applicationFilePath();

    // comma is used to specify a test function. In this case, an invalid one.
    debuggee.commandLineArguments = QString("-test QmlProfiler,");
    runControl = new ProjectExplorer::RunControl(nullptr,
                                                 ProjectExplorer::Constants::QML_PROFILER_RUN_MODE);
    runControl->setRunnable(debuggee);
    profiler = new LocalQmlProfilerSupport(&tool, runControl, serverUrl);
    connectRunner();
    runControl->initiateStart();

    QTRY_VERIFY_WITH_TIMEOUT(running, 30000);
    QTRY_VERIFY_WITH_TIMEOUT(!running, 30000);
    QCOMPARE(startCount, 2);
    QCOMPARE(stopCount, 2);
    QCOMPARE(runCount, 1);

    runControl->initiateFinish();
    QTRY_VERIFY(runControl.isNull());
    QVERIFY(profiler.isNull());

    debuggee.commandLineArguments.clear();
    serverUrl.clear();
    serverUrl = Utils::urlFromLocalHostAndFreePort();
    runControl = new ProjectExplorer::RunControl(nullptr,
                                                 ProjectExplorer::Constants::QML_PROFILER_RUN_MODE);
    runControl->setRunnable(debuggee);
    profiler = new LocalQmlProfilerSupport(&tool, runControl, serverUrl);
    connectRunner();
    runControl->initiateStart();

    QTRY_VERIFY_WITH_TIMEOUT(running, 30000);
    runControl->initiateStop();
    QTRY_VERIFY_WITH_TIMEOUT(!running, 30000);
    QCOMPARE(startCount, 3);
    QCOMPARE(stopCount, 3);
    QCOMPARE(runCount, 2);

    runControl->initiateFinish();
    QTRY_VERIFY(runControl.isNull());
    QVERIFY(profiler.isNull());

    debuggee.commandLineArguments = QString("-test QmlProfiler,");
    serverUrl.setScheme(Utils::urlSocketScheme());
    {
        Utils::TemporaryFile file("file with spaces");
        if (file.open())
            serverUrl.setPath(file.fileName());
    }

    runControl = new ProjectExplorer::RunControl(nullptr,
                                                 ProjectExplorer::Constants::QML_PROFILER_RUN_MODE);
    runControl->setRunnable(debuggee);
    profiler = new LocalQmlProfilerSupport(&tool, runControl, serverUrl);
    connectRunner();
    runControl->initiateStart();

    QTRY_VERIFY_WITH_TIMEOUT(running, 30000);
    QTRY_VERIFY_WITH_TIMEOUT(!running, 30000);
    QCOMPARE(startCount, 4);
    QCOMPARE(stopCount, 4);
    QCOMPARE(runCount, 3);

    runControl->initiateFinish();
    QTRY_VERIFY(runControl.isNull());
    QVERIFY(profiler.isNull());
}
Example #29
0
void tst_QGraphicsEffect::draw()
{
    QGraphicsScene scene;
    CustomItem *item = new CustomItem(0, 0, 100, 100);
    scene.addItem(item);

    QGraphicsView view(&scene);
    view.show();
    QTest::qWaitForWindowShown(&view);
    QTRY_VERIFY(item->numRepaints > 0);
    item->reset();

    // Make sure installing the effect triggers a repaint.
    CustomEffect *effect = new CustomEffect;
    item->setGraphicsEffect(effect);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);

    // Make sure QPainter* and QStyleOptionGraphicsItem* stays persistent
    // during QGraphicsEffect::draw/QGraphicsItem::paint.
    QVERIFY(effect->m_painter);
    QCOMPARE(effect->m_painter, item->m_painter);
    QCOMPARE(effect->m_styleOption, item->m_styleOption);
    // Make sure QGraphicsEffect::source is persistent.
    QCOMPARE(effect->m_source, effect->source());
    effect->reset();
    item->reset();

    // Make sure updating the source triggers a repaint.
    item->update();
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    QVERIFY(effect->m_sourceChangedFlags & QGraphicsEffect::SourceInvalidated);
    effect->reset();
    item->reset();

    // Make sure changing the effect's bounding rect triggers a repaint.
    effect->setMargin(20);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    // Make sure change the item's bounding rect triggers a repaint.
    item->setRect(0, 0, 50, 50);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    QVERIFY(effect->m_sourceChangedFlags & QGraphicsEffect::SourceBoundingRectChanged);
    effect->reset();
    item->reset();

    // Make sure the effect is the one to issue a repaint of the item.
    effect->doNothingInDraw = true;
    item->update();
    QTRY_COMPARE(effect->numRepaints, 1);
    QCOMPARE(item->numRepaints, 0);
    effect->doNothingInDraw = false;
    effect->reset();
    item->reset();

    // Make sure we update the source when disabling/enabling the effect.
    effect->setEnabled(false);
    QTest::qWait(50);
    QCOMPARE(effect->numRepaints, 0);
    QCOMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    effect->setEnabled(true);
    QTRY_COMPARE(effect->numRepaints, 1);
    QTRY_COMPARE(item->numRepaints, 1);
    effect->reset();
    item->reset();

    // Effect is already enabled; nothing should happen.
    effect->setEnabled(true);
    QTest::qWait(50);
    QCOMPARE(effect->numRepaints, 0);
    QCOMPARE(item->numRepaints, 0);

    // Make sure uninstalling an effect triggers a repaint.
    QPointer<CustomEffect> ptr = effect;
    item->setGraphicsEffect(0);
    QVERIFY(!ptr);
    QTRY_COMPARE(item->numRepaints, 1);
}
void tst_qsganimatedimage::progressAndStatusChanges()
{
    TestHTTPServer server(14449);
    QVERIFY(server.isValid());
    server.serveDirectory(SRCDIR "/data");

    QDeclarativeEngine engine;
    QString componentStr = "import QtQuick 2.0\nAnimatedImage { source: srcImage }";
    QDeclarativeContext *ctxt = engine.rootContext();
    ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/stickman.gif"));
    QDeclarativeComponent component(&engine);
    component.setData(componentStr.toLatin1(), QUrl::fromLocalFile(""));
    QSGImage *obj = qobject_cast<QSGImage*>(component.create());
    QVERIFY(obj != 0);
    QVERIFY(obj->status() == QSGImage::Ready);
    QTRY_VERIFY(obj->progress() == 1.0);

    QSignalSpy sourceSpy(obj, SIGNAL(sourceChanged(const QUrl &)));
    QSignalSpy progressSpy(obj, SIGNAL(progressChanged(qreal)));
    QSignalSpy statusSpy(obj, SIGNAL(statusChanged(QSGImageBase::Status)));

    // Loading local file
    ctxt->setContextProperty("srcImage", QUrl::fromLocalFile(SRCDIR "/data/colors.gif"));
    QTRY_VERIFY(obj->status() == QSGImage::Ready);
    QTRY_VERIFY(obj->progress() == 1.0);
    QTRY_COMPARE(sourceSpy.count(), 1);
    QTRY_COMPARE(progressSpy.count(), 0);
    QTRY_COMPARE(statusSpy.count(), 0);

    // Loading remote file
    ctxt->setContextProperty("srcImage", "http://127.0.0.1:14449/stickman.gif");
    QTRY_VERIFY(obj->status() == QSGImage::Loading);
    QTRY_VERIFY(obj->progress() == 0.0);
    QTRY_VERIFY(obj->status() == QSGImage::Ready);
    QTRY_VERIFY(obj->progress() == 1.0);
    QTRY_COMPARE(sourceSpy.count(), 2);
    QTRY_VERIFY(progressSpy.count() > 1);
    QTRY_COMPARE(statusSpy.count(), 2);

    ctxt->setContextProperty("srcImage", "");
    QTRY_VERIFY(obj->status() == QSGImage::Null);
    QTRY_VERIFY(obj->progress() == 0.0);
    QTRY_COMPARE(sourceSpy.count(), 3);
    QTRY_VERIFY(progressSpy.count() > 2);
    QTRY_COMPARE(statusSpy.count(), 3);
}