File indexing completed on 2025-01-05 04:37:32

0001 /*
0002     SPDX-FileCopyrightText: 2010 Joris Guisson <joris.guisson@gmail.com>
0003 
0004     SPDX-License-Identifier: GPL-2.0-or-later
0005 */
0006 
0007 #include <QObject>
0008 #include <QtTest>
0009 #include <util/log.h>
0010 #include <utp/connection.h>
0011 #include <utp/utpserver.h>
0012 
0013 using namespace utp;
0014 
0015 class FinTest : public QEventLoop
0016 {
0017 public:
0018     void accepted()
0019     {
0020         incoming = srv.acceptedConnection().toStrongRef();
0021         exit();
0022     }
0023 
0024     void endEventLoop()
0025     {
0026         exit();
0027     }
0028 
0029 private:
0030     void initTestCase()
0031     {
0032         bt::InitLog("fintest.log");
0033 
0034         port = 50000;
0035         while (port < 60000) {
0036             if (!srv.changePort(port))
0037                 port++;
0038             else
0039                 break;
0040         }
0041 
0042         srv.setCreateSockets(false);
0043         srv.start();
0044     }
0045 
0046     void cleanupTestCase()
0047     {
0048         srv.stop();
0049     }
0050 
0051     void testConnect()
0052     {
0053         net::Address addr("127.0.0.1", port);
0054         connect(&srv, &utp::UTPServer::accepted, this, &FinTest::accepted, Qt::QueuedConnection);
0055         outgoing = srv.connectTo(addr).toStrongRef();
0056         QVERIFY(outgoing);
0057         QTimer::singleShot(5000, this, &FinTest::endEventLoop); // use a 5 second timeout
0058         exec();
0059         QVERIFY(incoming);
0060     }
0061 
0062     void testFin()
0063     {
0064         bt::Out(SYS_UTP | LOG_DEBUG) << "testFin" << bt::endl;
0065         if (outgoing->connectionState() != CS_CONNECTED || incoming->connectionState() != CS_CONNECTED) {
0066             QSKIP("Not Connected", SkipAll);
0067             return;
0068         }
0069 
0070         char test[] = "This is the fin test";
0071         outgoing->send((const bt::Uint8 *)test, strlen(test));
0072         incoming->setBlocking(true);
0073         if (incoming->waitForData()) {
0074             bt::Uint8 tmp[100];
0075             memset(tmp, 0, 100);
0076             int ret = incoming->recv(tmp, 100);
0077             QVERIFY(ret == (int)strlen(test));
0078             QVERIFY(memcmp(tmp, test, strlen(test)) == 0);
0079 
0080             outgoing->close();
0081             if (incoming->connectionState() != CS_CLOSED)
0082                 incoming->waitForData();
0083 
0084             // connection should be closed now
0085             ret = incoming->recv(tmp, 100);
0086             QVERIFY(incoming->connectionState() == CS_CLOSED);
0087             QVERIFY(ret == -1);
0088         } else
0089             QFAIL("No data received");
0090     }
0091 
0092 private:
0093     utp::UTPServer srv;
0094     int port;
0095     Connection::Ptr incoming;
0096     Connection::Ptr outgoing;
0097 };
0098 
0099 QTEST_MAIN(FinTest)