Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Problem with a QTcpServer and a UnitTest



  • Hello all,

    i have call MyServer that listens on a specific TCP port for incoming connections and sends some data when a connection has been established.
    Therefore i made some unit tests (to get used to the qt test library). MyServer belongs to a library, which is a Qt library project. Then I have a project Tests that uses the subdirs template. Inside the MyServer subproject as Unit test.

    The tests for connection establishment work fine, then I want to check if the server sends the data as it is supposed to do. My primal version of the test looks like this:
    @
    MyServer srv(nullptr);
    QTcpSocket tcp;
    tcp.connectToHost("127.0.0.1", 9997);
    tcp.waitForConnected(3000);
    QVERIFY(tcp.state() == QAbstractSocket::ConnectedState);
    QVERIFY(tcp.bytesAvailable() > 0);
    @

    The second verify always fails. However, if I build an own console application performing the same operations the data arrives.
    What is the problem?

    Thank you!

    Regards


  • Lifetime Qt Champion

    Hi,

    You don't let any time for the data to arrive.

    @
    tcp.waitForConnected(3000);
    QVERIFY(tcp.state() == QAbstractSocket::ConnectedState);
    QVERIFY(tcp.bytesAvailable() > 0);
    @

    These three will be called one after the other without any pause. You should wait some milliseconds using qWait to let the event loop run



  • Thanks for the fast response, i already thought something like this and tried QThread::msleep()... but this couldn't work since it also blocks execution of the event loop I suppose.

    Unfortunately this now leads to an error. The data are sent by the server in the slot for the signal newConnection, but sending can also be triggered manually.
    @
    tcp.connectToHost("127.0.0.1", 9997);
    tcp.waitForConnected(3000);
    QVERIFY(tcp.state() == QAbstractSocket::ConnectedState);
    QTest::qWait(1000);
    srv.sendData();
    QTest::qWait(1000);
    QVERIFY(tcp.bytesAvailable() > 0);
    @

    The error is:
    QFATAL : MyServerTest::retrieveInitialDataAfterConnection() ASSERT: "QCoreApplication::instance()" in file C:\Qt\5.2.0\mingw48_32\include/QtTest/qtestsystem.h, line 61

    sendData contains some output via std:cerr, hence it is written in the test output when executed. When i comment the first occurence of qWait the output occurs, when using the two qWait the output is not present and the above error occurs twice in a row. and the last verify is not evaluated. Is the test still wrong?

    At the bottom my test looks like this:
    @
    QTEST_APPLESS_MAIN(MyServerTest)

    #include "tst_myservertest.moc"
    @


  • Lifetime Qt Champion

    You don't have an application, change QTEST_APPLESS_MAIN to QTEST_MAIN


Log in to reply