summaryrefslogtreecommitdiffstats
path: root/tests/nfcsymbianbackend/qllcpsocketlocal/tst_qllcpsocketlocal.cpp
blob: fa295fc2fa1b5196e33dc1758d2226551092c794 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtNfc module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 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 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QString>
#include <QtTest/QtTest>
#include <QtCore/QCoreApplication>

#include <qllcpsocket.h>
#include <qnearfieldmanager.h>
#include <qnearfieldtarget.h>
#include "qnfctestcommon.h"
#include "qnfctestutil.h"

Q_DECLARE_METATYPE(QNearFieldTarget*)
Q_DECLARE_METATYPE(QLlcpSocket::SocketError )
Q_DECLARE_METATYPE(QLlcpSocket::SocketState )

class tst_qllcpsocketlocal : public QObject
{
    Q_OBJECT

public:
    tst_qllcpsocketlocal();
private Q_SLOTS:


    void multipleClient();
    void echoClient();
    void echoClient_data();
    void testCase2();   //work with  tst_qllcpsocketremote testCase2
    void testCase3();
    void coverageTest1();
    //advanced test
    void deleteSocketWhenInUse();
    void waitBytesWrittenInSlot();
    void multiSocketToOneServer();
    //negtive test
    void negTestCase1();
    void negTestCase2();
    //void negTestCase3();
    //void negTestCase4();

    void initTestCase();
    void cleanupTest();

private:
    void writeMessage(QLlcpSocket& localSocket,QString& payLoad);
private:
     QNearFieldTarget *m_target; // not own
     quint8 m_port;
};

tst_qllcpsocketlocal::tst_qllcpsocketlocal()
{
    qRegisterMetaType<QNearFieldTarget *>("QNearFieldTarget*");
    qRegisterMetaType<QLlcpSocket::SocketError>("QLlcpSocket::SocketError");
    qRegisterMetaType<QLlcpSocket::SocketState>("QLlcpSocket::SocketState");
}

/*!
 Description: Init test case for NFC LLCP connection-less mode socket - local peer

 TestScenario:
     Touch a NFC device with LLCP connection-less service actived

 TestExpectedResults:
     Signal of target detected has been found.
*/
void tst_qllcpsocketlocal::initTestCase()
{
    qDebug()<<"tst_qllcpsocketlocal::initTestCase() Begin";
    QString message("Please touch a NFC device with llcp client enabled");
    QNearFieldManager nfcManager;
    QSignalSpy targetDetectedSpy(&nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)));
    nfcManager.startTargetDetection(QNearFieldTarget::NfcForumDevice);

    QNfcTestUtil::ShowAutoMsg(message, &targetDetectedSpy, 1);
    QTRY_VERIFY(!targetDetectedSpy.isEmpty());

    m_target = targetDetectedSpy.at(targetDetectedSpy.count() - 1).at(0).value<QNearFieldTarget*>();
    QVERIFY(m_target != NULL);
    QVERIFY(m_target->accessMethods() & QNearFieldTarget::LlcpAccess);
    QVERIFY(m_target->uid() == QByteArray());
    QVERIFY(m_target->type() == QNearFieldTarget::NfcForumDevice);

    m_port = 35;
    qDebug()<<"tst_qllcpsocketlocal::initTestCase() End";
}

/*!
 Description: Send the message and Receive the acknowledged identical message

 TestScenario:
           1. Local peer temps to read datagram without bind
           2. Local peer binds to the remote peer
           3. Local peer sends the "testcase1 string" message to the remote peer
           4. Local peer receives the above message sending from the remote peer

 TestExpectedResults:
           1. Local peer fails to read datagram without bind
           2. Local peer binds to local port successfully.
           3. The message has be sent to remote peer.
           4. The message has been received from remote peer.
*/
void tst_qllcpsocketlocal::echoClient()
{
    QFETCH(QString, echoPayload);
    QLlcpSocket localSocket;

    // STEP 1.  readDatagram must be called before bind
    QByteArray tmpForReadArray;
    tmpForReadArray.resize(127);
    qint64 ret = localSocket.readDatagram(tmpForReadArray.data(), tmpForReadArray.size());
    QVERIFY(ret == -1);

    QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState);
    QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)));

    // STEP 2:  bind the local port for current socket
    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool retBool = localSocket.bind(m_port);
    QVERIFY(retBool);
    QVERIFY(!stateChangedSpy.isEmpty());
    QCOMPARE(localSocket.state(), QLlcpSocket::BoundState);

    // Wait remote part bind
    QString messageBox("Wait remote bind");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    // STEP 3: Local peer sends the  message to the remote peer
    writeMessage(localSocket,echoPayload);
    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState)));

    // STEP 4: Start read payload from server
    QString messageBox2("Wait remote send buffer");
    QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy);

    QByteArray inPayload;
    while(localSocket.hasPendingDatagrams()) {
        QByteArray tempBuffer;
        tempBuffer.resize(localSocket.pendingDatagramSize());
        quint8 remotePort = 0;
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                   , tempBuffer.size()
                                                   , &m_target, &remotePort);
        QVERIFY(readSize != -1);
        QVERIFY(remotePort > 0);
        inPayload.append(tempBuffer);
        qDebug() << "Client-- read inPayload size=" << inPayload.size();
        qDebug() << "Client-- read remotePort=" << remotePort;
        if (inPayload.size() >= (int)sizeof(quint16)) {
            break;
        }
        else
        {
            qDebug() << "Client-- not enough header";
            QTRY_VERIFY(!readyRead.isEmpty());
        }
    }

    QDataStream in(inPayload);
    in.setVersion(QDataStream::Qt_4_6);
    quint16 headerSize = 0; // size of real echo payload
    in >> headerSize;
    qDebug() << "Client-- read headerSize=" << headerSize;
    while (inPayload.size() < headerSize + (int)sizeof(quint16)){
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        QTRY_VERIFY(!readyRead.isEmpty());
        if(localSocket.hasPendingDatagrams()) {
            QByteArray tempBuffer;
            tempBuffer.resize(localSocket.pendingDatagramSize());
            quint8 remotePort = 0;
            qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                       , tempBuffer.size()
                                                       , &m_target, &remotePort);
            QVERIFY(readSize != -1);
            QVERIFY(remotePort > 0);
            inPayload.append(tempBuffer);
            qDebug() << "Client-- read long blocksize=" << inPayload.size();
        }
    }

    QDataStream in2(inPayload);
    in2.setVersion(QDataStream::Qt_4_6);
    in2 >> headerSize;
    QString inEchoPayload;
    in2 >> inEchoPayload;
    qDebug() << "Client-- in echo string len:" << inEchoPayload.length();
    qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload));
    //test the echoed string is same as the original string
    QVERIFY(echoPayload == inEchoPayload);
    // make sure the no error signal emitted
    QVERIFY(errorSpy.isEmpty());
}

void tst_qllcpsocketlocal::echoClient_data()
{
    QTest::addColumn<QString>("echoPayload");
    QTest::newRow("0") << "test payload";
    QString longStr4k;
    for (int i = 0; i < 4000; i++)
        longStr4k.append((char)(i%26 + 'a'));
    QTest::newRow("1") << longStr4k;
}

void tst_qllcpsocketlocal::writeMessage(
                          QLlcpSocket& localSocket,
                          QString& payLoad)
{
    // STEP 2: Local peer sends the  message to the remote peer
    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState)));
    QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64)));

    //Prepare data to send
    QByteArray outPayload;
    QDataStream out(&outPayload, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << payLoad;

    qDebug("Client-- write quint16 length = %d", sizeof(quint16));
    qDebug("Client-- write echo string = %s", qPrintable(payLoad));
    qDebug("Client-- write echo string length= %d", payLoad.length());
    qDebug("Client-- write payload length = %d", outPayload.length());
    out.device()->seek(0);
    out << (quint16)(outPayload.size() - sizeof(quint16));

    qint64 ret = localSocket.writeDatagram(outPayload, m_target, m_port);
    QVERIFY(ret == 0);

    QTRY_VERIFY(!bytesWrittenSpy.isEmpty());

    qint64 written = 0;
    qint32 lastSignalCount = 0;
    while(true)
    {
       for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) {
           written += bytesWrittenSpy.at(i).at(0).value<qint64>();
       }
       lastSignalCount = bytesWrittenSpy.count();
       qDebug() << "current signal count = " << lastSignalCount;
       qDebug() << "written payload size = " << written;
       if (written < outPayload.size()) {
           QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount);
       }
       else {
           break;
       }
    }
    qDebug() << "Overall bytesWritten = " << written;
    qDebug() << "Overall block size = " << outPayload.size();
    QVERIFY(written == outPayload.size());
}


/*!
 Description: Send the message and Receive the acknowledged identical message

 TestScenario:
           1. Local peer sends the very long message to the remote peer
           2. Local peer sends the second very long message to the remote peer

 TestExpectedResults:
           1. The message has be sent to remote peer.
           2. The second message has been received from remote peer.
*/
void tst_qllcpsocketlocal::multipleClient()
{
    QLlcpSocket localSocket;
    QString longStr1k;
    for (int i = 0; i < 1000; i++)
        longStr1k.append((char)(i%26 + 'a'));

    QString longStr2k;
    for (int i = 0; i < 2000; i++)
        longStr2k.append((char)(i%26 + 'b'));

    QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState);
    QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)));

    // STEP 1:  bind the local port for current socket
    bool retBool = localSocket.bind(m_port);
    QVERIFY(retBool);
    QVERIFY(!stateChangedSpy.isEmpty());
    QCOMPARE(localSocket.state(), QLlcpSocket::BoundState);

    // Wait remote part bind
    QString messageBox("Wait remote bind");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    writeMessage(localSocket,longStr1k);
    writeMessage(localSocket,longStr2k);
}


void tst_qllcpsocketlocal::testCase2()
{
    QLlcpSocket localSocket;
    quint8 localPort = 38;

    // STEP 1:
    //QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64)));
    QString message("testcase2 string str1");
    QByteArray tmpArray(message.toAscii());
    const char* data =  tmpArray.data();
    qint64 strSize = message.size();
    qint64 val = localSocket.writeDatagram(data, strSize, m_target, localPort);
    QVERIFY(val != -1);

    // STEP 2:
    QString message2("testcase2 string str2");
    QByteArray tmpArray2(message2.toAscii());
    const char* data2 =  tmpArray2.data();
    qint64 strSize2 = message2.size();
    qint64 val2 = localSocket.writeDatagram(data2, strSize2, m_target, localPort);
    QVERIFY(val2 != -1);

    // STEP 3:
    const int Timeout = 2 * 1000;
    bool ret = localSocket.waitForBytesWritten(Timeout);
    QVERIFY(ret);

     // STEP 4:
    ret = localSocket.waitForBytesWritten(Timeout);
    QVERIFY(ret);

    QString messageBox("handshake 3");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    // STEP 5: Try to cover waitForBytesWritten() in bound mode
    const int Timeout1 = 1 * 1000;
    localSocket.waitForBytesWritten(Timeout1);
    QVERIFY(ret);
}

/*!
 Description: coverage testcase - targeted for sender doCancel
*/
void tst_qllcpsocketlocal::testCase3()
{
    QLlcpSocket localSocket;
    // STEP 1:
    QString message("string1");
    QByteArray tmpArray(message.toAscii());
    const char* data =  tmpArray.data();
    qint64 strSize = message.size();
    localSocket.writeDatagram(data,strSize,m_target, m_port);
}

/*!
 Description: coverage testcase - invalid usage of connection-oriented API
*/
void tst_qllcpsocketlocal::coverageTest1()
{
    QLlcpSocket localSocket;

    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketError)));
    localSocket.connectToService(m_target,"uri");
    QTRY_VERIFY(errorSpy.count() == 1);
    QVERIFY(localSocket.error() == QLlcpSocket::UnknownSocketError);

    localSocket.disconnectFromService();
    QTRY_VERIFY(errorSpy.count() == 2);

    QVERIFY(localSocket.waitForConnected() == false);
    QVERIFY(localSocket.waitForDisconnected() == false);

    QString message = "Oops, must follow a port parameter";
    QByteArray tmpArray(message.toAscii());
    const char* data =  tmpArray.data();
    qint64 strSize = message.size();
    qint64 ret = localSocket.writeDatagram(data,strSize);
    QVERIFY(ret == -1);
}

class BytesWrittenSlot : public QObject
{
    Q_OBJECT
public:
    BytesWrittenSlot(QLlcpSocket* s): m_socket(s)
        {
        connect(m_socket,SIGNAL(bytesWritten(qint64)),this,SLOT(gotBytesWritten(qint64)));
        }
private slots:
    void gotBytesWritten(qint64 w)
        {
        qDebug()<<"In BytesWrittenSlot: Delete the socket when still alive...";
        delete m_socket;
        }
private:
    QLlcpSocket* m_socket;
};
/*!
 Description: Add a case to test delete the socket in the slot when the transmission is still alive.
 CounterPart test: tst_qllcpsocketremote::dumpServer()
*/
void tst_qllcpsocketlocal::deleteSocketWhenInUse()
    {
    QString message("deleteSocketWhenInUse test");
    QNfcTestUtil::ShowAutoMsg(message);

    QLlcpSocket* socket = new QLlcpSocket;

    bool retBool = socket->bind(m_port);
    QVERIFY(retBool);

    // STEP 3: Local peer sends the  message to the remote peer
    QSignalSpy errorSpy(socket, SIGNAL(error(QLlcpSocket::SocketState)));

    BytesWrittenSlot slot(socket);

    QString echo;
    for (int i = 0; i < 2000; i++)
        echo.append((char)(i%26 + 'a'));
    //Prepare data to send
    QByteArray outPayload;
    QDataStream out(&outPayload, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << echo;

    out.device()->seek(0);
    out << (quint16)(outPayload.size() - sizeof(quint16));

    bool ret = socket->writeDatagram(outPayload, m_target, m_port);
    QVERIFY(ret == 0);

    QTest::qWait(5 * 1000);//give some time to wait bytesWritten signal
    QVERIFY(errorSpy.isEmpty());

    }

class WaitBytesWrittenSlot : public QObject
{
    Q_OBJECT
public:
    WaitBytesWrittenSlot(QLlcpSocket& s): m_socket(s),m_signalCount(0)
        {
        connect(&m_socket,SIGNAL(bytesWritten(qint64)),this,SLOT(gotBytesWritten(qint64)));
        }
private slots:
void gotBytesWritten(qint64 w)
        {
        m_signalCount++;
        qDebug()<<"Got BytesWritten() signal number = "<<m_signalCount;
        const int Timeout = 50;//3* 1000 seems too long, nfc server will panic spray signal
        bool ret = m_socket.waitForBytesWritten(Timeout);
        if (!ret)
            {
            qDebug()<<"WaitBytesWrittenSlot() in slot of ReadyRead signal return false";
            }
        else
            {
            qDebug()<<"WaitBytesWrittenSlot() in slot of ReadyRead signal return true";
            }
        }
private:
    QLlcpSocket& m_socket;
    int m_signalCount;
};
/*!
 Description: Test WaitForBytesWritten() in slot of
 bytesWritten signal, make sure the signal will not
 be emitted twice in the slot function.
 CounterPart test: tst_qllcpsocketremote::echoServer()
*/
void tst_qllcpsocketlocal::waitBytesWrittenInSlot()
{
    QLlcpSocket localSocket;

    QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState);
    QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)));

    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool retBool = localSocket.bind(m_port);
    QVERIFY(retBool);
    QVERIFY(!stateChangedSpy.isEmpty());
    QCOMPARE(localSocket.state(), QLlcpSocket::BoundState);

    // Wait remote part bind
    QString messageBox("Wait remote bind");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    // STEP 3: Local peer sends the  message to the remote peer
    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState)));
    QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64)));

    WaitBytesWrittenSlot slot(localSocket);

    QString echoPayload;
    for (int i = 0; i < 2000; i++)
        echoPayload.append((char)(i%26 + 'a'));
    //Prepare data to send
    QByteArray outPayload;
    QDataStream out(&outPayload, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << echoPayload;

    out.device()->seek(0);
    out << (quint16)(outPayload.size() - sizeof(quint16));

    bool ret = localSocket.writeDatagram(outPayload, m_target, m_port);
    QVERIFY(ret == 0);

    QTRY_VERIFY(!bytesWrittenSpy.isEmpty());

    qint64 written = 0;
    qint32 lastSignalCount = 0;
    while(true)
    {
        for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) {
            written += bytesWrittenSpy.at(i).at(0).value<qint64>();
        }
        lastSignalCount = bytesWrittenSpy.count();
        qDebug() << "current signal count = " << lastSignalCount;
        qDebug() << "written payload size = " << written;
        if (written < outPayload.size()) {
            QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount);
        }
        else {
            break;
        }
    }
    qDebug() << "Overall bytesWritten = " << written;
    qDebug() << "Overall block size = " << outPayload.size();
    QVERIFY(written == outPayload.size());

    // STEP 4: Start read payload from server
    QString messageBox2("Wait remote send buffer");
    QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy);

    QByteArray inPayload;
    while(localSocket.hasPendingDatagrams()) {
        QByteArray tempBuffer;
        tempBuffer.resize(localSocket.pendingDatagramSize());
        quint8 remotePort = 0;
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                   , tempBuffer.size()
                                                   , &m_target, &remotePort);
        QVERIFY(readSize != -1);
        QVERIFY(remotePort > 0);
        inPayload.append(tempBuffer);
        qDebug() << "Client-- read inPayload size=" << inPayload.size();
        qDebug() << "Client-- read remotePort=" << remotePort;
        if (inPayload.size() >= (int)sizeof(quint16)) {
            break;
        }
        else
        {
            qDebug() << "Client-- not enough header";
            QTRY_VERIFY(!readyRead.isEmpty());
        }
    }

    QDataStream in(inPayload);
    in.setVersion(QDataStream::Qt_4_6);
    quint16 headerSize = 0; // size of real echo payload
    in >> headerSize;
    qDebug() << "Client-- read headerSize=" << headerSize;
    while (inPayload.size() < headerSize + (int)sizeof(quint16)){
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        QTRY_VERIFY(!readyRead.isEmpty());
        if(localSocket.hasPendingDatagrams()) {
            QByteArray tempBuffer;
            tempBuffer.resize(localSocket.pendingDatagramSize());
            quint8 remotePort = 0;
            qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                       , tempBuffer.size()
                                                       , &m_target, &remotePort);
            QVERIFY(readSize != -1);
            QVERIFY(remotePort > 0);
            inPayload.append(tempBuffer);
            qDebug() << "Client-- read long blocksize=" << inPayload.size();
        }
    }

    QDataStream in2(inPayload);
    in2.setVersion(QDataStream::Qt_4_6);
    in2 >> headerSize;
    QString inEchoPayload;
    in2 >> inEchoPayload;
    qDebug() << "Client-- in echo string len:" << inEchoPayload.length();
    qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload));
    //test the echoed string is same as the original string
    QVERIFY(echoPayload == inEchoPayload);
    // make sure the no error signal emitted
    QVERIFY(errorSpy.isEmpty());
}
/*!
 Description: writeDatagram negative testcase I - invalid port num & wait* functions
*/
void tst_qllcpsocketlocal::negTestCase1()
{
    QLlcpSocket localSocket;
    QString message = "Oops, Invalid port num for writeDatagram";
    QByteArray tmpArray(message.toAscii());
    const char* data =  tmpArray.data();
    qint64 strSize = message.size();
    qint8 invalidPort = -1;
    qint64 ret = localSocket.writeDatagram(data,strSize,m_target, invalidPort);
    QVERIFY(ret == -1);

    const int Timeout = 1 * 500;
    bool retBool = localSocket.waitForBytesWritten(Timeout);
    QVERIFY(!retBool);

    //Cover QLLCPUnConnected::WaitForReadyRead
    retBool = localSocket.waitForReadyRead(Timeout);
    QVERIFY(!retBool);

    //Cover QLLCPBind::WaitForReadyRead()
    retBool = localSocket.waitForReadyRead(Timeout);
    QVERIFY(!retBool);
}

/*!
 Description: bind negative test - double bind
*/
void tst_qllcpsocketlocal::negTestCase2()
{
    QLlcpSocket localSocket1;
    QLlcpSocket localSocket2;
    // bind again will cause failure
    bool ret2 = localSocket1.bind(m_port);
    QVERIFY(ret2);
    ret2 = localSocket2.bind(m_port);
    QVERIFY(!ret2);
}

/*!
 Description: bind negative test - invalid port num
*/
/*
void tst_qllcpsocketlocal::negTestCase3()
{
    QLlcpSocket localSocket;
    bool ret = localSocket.bind(65);
    QVERIFY(ret == false);
}
*/

/*!
 Description: bind negative test - invalid port num II
*/
/*
void tst_qllcpsocketlocal::negTestCase4()
{
    QLlcpSocket localSocket;
    int reservedPort = 15;
    bool ret = localSocket.bind(reservedPort);
    QVERIFY(ret == false);
}
*/
void tst_qllcpsocketlocal::multiSocketToOneServer()
{
    QString echoPayload = "multiSocketToOneServer";
    {
    QLlcpSocket localSocket;


    QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState);
    QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)));

    // STEP 2:  bind the local port for current socket
    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool retBool = localSocket.bind(m_port);
    QVERIFY(retBool);
    QVERIFY(!stateChangedSpy.isEmpty());
    QCOMPARE(localSocket.state(), QLlcpSocket::BoundState);

    // Wait remote part bind
    QString messageBox("Wait remote bind");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    // STEP 3: Local peer sends the  message to the remote peer
    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState)));
    QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64)));

    //Prepare data to send
    QByteArray outPayload;
    QDataStream out(&outPayload, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << echoPayload;

    qDebug("Client-- write quint16 length = %d", sizeof(quint16));
    qDebug("Client-- write echo string length= %d", echoPayload.length());
    qDebug("Client-- write payload length = %d", outPayload.length());
    out.device()->seek(0);
    out << (quint16)(outPayload.size() - sizeof(quint16));

    bool ret = localSocket.writeDatagram(outPayload, m_target, m_port);
    QVERIFY(ret == 0);

    QTRY_VERIFY(!bytesWrittenSpy.isEmpty());

    qint64 written = 0;
    qint32 lastSignalCount = 0;
    while(true)
    {
        for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) {
            written += bytesWrittenSpy.at(i).at(0).value<qint64>();
        }
        lastSignalCount = bytesWrittenSpy.count();
        qDebug() << "current signal count = " << lastSignalCount;
        qDebug() << "written payload size = " << written;
        if (written < outPayload.size()) {
            QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount);
        }
        else {
            break;
        }
    }
    qDebug() << "Overall bytesWritten = " << written;
    qDebug() << "Overall block size = " << outPayload.size();
    QVERIFY(written == outPayload.size());

    // STEP 4: Start read payload from server
    QString messageBox2("Wait remote send buffer");
    QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy);

    QByteArray inPayload;
    while(localSocket.hasPendingDatagrams()) {
        QByteArray tempBuffer;
        tempBuffer.resize(localSocket.pendingDatagramSize());
        quint8 remotePort = 0;
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                   , tempBuffer.size()
                                                   , &m_target, &remotePort);
        QVERIFY(readSize != -1);
        QVERIFY(remotePort > 0);
        inPayload.append(tempBuffer);
        qDebug() << "Client-- read inPayload size=" << inPayload.size();
        qDebug() << "Client-- read remotePort=" << remotePort;
        if (inPayload.size() >= (int)sizeof(quint16)) {
            break;
        }
        else
        {
            qDebug() << "Client-- not enough header";
            QTRY_VERIFY(!readyRead.isEmpty());
        }
    }

    QDataStream in(inPayload);
    in.setVersion(QDataStream::Qt_4_6);
    quint16 headerSize = 0; // size of real echo payload
    in >> headerSize;
    qDebug() << "Client-- read headerSize=" << headerSize;
    while (inPayload.size() < headerSize + (int)sizeof(quint16)){
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        QTRY_VERIFY(!readyRead.isEmpty());
        if(localSocket.hasPendingDatagrams()) {
            QByteArray tempBuffer;
            tempBuffer.resize(localSocket.pendingDatagramSize());
            quint8 remotePort = 0;
            qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                       , tempBuffer.size()
                                                       , &m_target, &remotePort);
            QVERIFY(readSize != -1);
            QVERIFY(remotePort > 0);
            inPayload.append(tempBuffer);
            qDebug() << "Client-- read long blocksize=" << inPayload.size();
        }
    }

    QDataStream in2(inPayload);
    in2.setVersion(QDataStream::Qt_4_6);
    in2 >> headerSize;
    QString inEchoPayload;
    in2 >> inEchoPayload;
    qDebug() << "Client-- in echo string len:" << inEchoPayload.length();
    qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload));
    //test the echoed string is same as the original string
    QVERIFY(echoPayload == inEchoPayload);
    // make sure the no error signal emitted
    QVERIFY(errorSpy.isEmpty());

    }
    {
    QLlcpSocket localSocket;


    QCOMPARE(localSocket.state(), QLlcpSocket::UnconnectedState);
    QSignalSpy stateChangedSpy(&localSocket, SIGNAL(stateChanged(QLlcpSocket::SocketState)));

    // STEP 2:  bind the local port for current socket
    QSignalSpy readyReadSpy(&localSocket, SIGNAL(readyRead()));
    bool retBool = localSocket.bind(m_port);
    QVERIFY(retBool);
    QVERIFY(!stateChangedSpy.isEmpty());
    QCOMPARE(localSocket.state(), QLlcpSocket::BoundState);

    // Wait remote part bind
    QString messageBox("Wait remote bind");
    QNfcTestUtil::ShowAutoMsg(messageBox);

    // STEP 3: Local peer sends the  message to the remote peer
    QSignalSpy errorSpy(&localSocket, SIGNAL(error(QLlcpSocket::SocketState)));
    QSignalSpy bytesWrittenSpy(&localSocket, SIGNAL(bytesWritten(qint64)));

    //Prepare data to send
    QByteArray outPayload;
    QDataStream out(&outPayload, QIODevice::WriteOnly);
    out.setVersion(QDataStream::Qt_4_6);
    out << (quint16)0;
    out << echoPayload;

    qDebug("Client-- write quint16 length = %d", sizeof(quint16));
    qDebug("Client-- write echo string length= %d", echoPayload.length());
    qDebug("Client-- write payload length = %d", outPayload.length());
    out.device()->seek(0);
    out << (quint16)(outPayload.size() - sizeof(quint16));

    bool ret = localSocket.writeDatagram(outPayload, m_target, m_port);
    QVERIFY(ret == 0);

    QTRY_VERIFY(!bytesWrittenSpy.isEmpty());

    qint64 written = 0;
    qint32 lastSignalCount = 0;
    while(true)
    {
        for(int i = lastSignalCount; i < bytesWrittenSpy.count(); i++) {
            written += bytesWrittenSpy.at(i).at(0).value<qint64>();
        }
        lastSignalCount = bytesWrittenSpy.count();
        qDebug() << "current signal count = " << lastSignalCount;
        qDebug() << "written payload size = " << written;
        if (written < outPayload.size()) {
            QTRY_VERIFY(bytesWrittenSpy.count() > lastSignalCount);
        }
        else {
            break;
        }
    }
    qDebug() << "Overall bytesWritten = " << written;
    qDebug() << "Overall block size = " << outPayload.size();
    QVERIFY(written == outPayload.size());

    // STEP 4: Start read payload from server
    QString messageBox2("Wait remote send buffer");
    QNfcTestUtil::ShowAutoMsg(messageBox2, &readyReadSpy);

    QByteArray inPayload;
    while(localSocket.hasPendingDatagrams()) {
        QByteArray tempBuffer;
        tempBuffer.resize(localSocket.pendingDatagramSize());
        quint8 remotePort = 0;
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                   , tempBuffer.size()
                                                   , &m_target, &remotePort);
        QVERIFY(readSize != -1);
        QVERIFY(remotePort > 0);
        inPayload.append(tempBuffer);
        qDebug() << "Client-- read inPayload size=" << inPayload.size();
        qDebug() << "Client-- read remotePort=" << remotePort;
        if (inPayload.size() >= (int)sizeof(quint16)) {
            break;
        }
        else
        {
            qDebug() << "Client-- not enough header";
            QTRY_VERIFY(!readyRead.isEmpty());
        }
    }

    QDataStream in(inPayload);
    in.setVersion(QDataStream::Qt_4_6);
    quint16 headerSize = 0; // size of real echo payload
    in >> headerSize;
    qDebug() << "Client-- read headerSize=" << headerSize;
    while (inPayload.size() < headerSize + (int)sizeof(quint16)){
        QSignalSpy readyRead(&localSocket, SIGNAL(readyRead()));
        QTRY_VERIFY(!readyRead.isEmpty());
        if(localSocket.hasPendingDatagrams()) {
            QByteArray tempBuffer;
            tempBuffer.resize(localSocket.pendingDatagramSize());
            quint8 remotePort = 0;
            qint64 readSize = localSocket.readDatagram(tempBuffer.data()
                                                       , tempBuffer.size()
                                                       , &m_target, &remotePort);
            QVERIFY(readSize != -1);
            QVERIFY(remotePort > 0);
            inPayload.append(tempBuffer);
            qDebug() << "Client-- read long blocksize=" << inPayload.size();
        }
    }

    QDataStream in2(inPayload);
    in2.setVersion(QDataStream::Qt_4_6);
    in2 >> headerSize;
    QString inEchoPayload;
    in2 >> inEchoPayload;
    qDebug() << "Client-- in echo string len:" << inEchoPayload.length();
    qDebug("Client-- in echo string = %s", qPrintable(inEchoPayload));
    //test the echoed string is same as the original string
    QVERIFY(echoPayload == inEchoPayload);
    // make sure the no error signal emitted
    QVERIFY(errorSpy.isEmpty());

    }

}
void tst_qllcpsocketlocal::cleanupTest()
{
}

QTEST_MAIN(tst_qllcpsocketlocal);

#include "tst_qllcpsocketlocal.moc"