summaryrefslogtreecommitdiffstats
path: root/tests/auto/corelib/thread/qfuturewatcher/tst_qfuturewatcher.cpp
blob: 40aa89ded4a2df9c57c1df66e2aa570799d8810f (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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only
#include <QCoreApplication>
#include <QDebug>
#include <QElapsedTimer>
#include <QSignalSpy>

#include <QtConcurrent>
#include <private/qfutureinterface_p.h>

using namespace QtConcurrent;
using namespace std::chrono_literals;

#include <QTest>

//#define PRINT

class tst_QFutureWatcher: public QObject
{
    Q_OBJECT
private slots:
    void startFinish();
    void progressValueChanged();
    void canceled();
    void cancelAndFinish_data();
    void cancelAndFinish();
    void resultAt();
    void resultReadyAt();
    void orderedResultReadyAt();
    void futureSignals();
    void watchFinishedFuture();
    void watchCanceledFuture();
    void disconnectRunningFuture();
    void tooMuchProgress();
    void progressText();
    void sharedFutureInterface();
    void changeFuture();
    void cancelEvents();
#if QT_DEPRECATED_SINCE(6, 0)
    void pauseEvents();
    void pausedSuspendedOrder();
#endif
    void suspendEvents();
    void suspended();
    void suspendedEventsOrder();
    void throttling();
    void incrementalMapResults();
    void incrementalFilterResults();
    void qfutureSynchronizer();
    void warnRace();
    void matchFlags();
    void checkStateConsistency();
};

void sleeper()
{
    QTest::qSleep(100);
}

void tst_QFutureWatcher::startFinish()
{
    QFutureWatcher<void> futureWatcher;

    int startedCount = 0;
    int finishedCount = 0;
    QObject::connect(&futureWatcher, &QFutureWatcher<void>::started,
                     [&startedCount, &finishedCount](){
        ++startedCount;
        QCOMPARE(startedCount, 1);
        QCOMPARE(finishedCount, 0);
    });
    QObject::connect(&futureWatcher, &QFutureWatcher<void>::finished,
                     [&startedCount, &finishedCount](){
        ++finishedCount;
        QCOMPARE(startedCount, 1);
        QCOMPARE(finishedCount, 1);
    });

    futureWatcher.setFuture(QtConcurrent::run(sleeper));
    futureWatcher.future().waitForFinished();

    // waitForFinished() may unblock before asynchronous
    // started() and finished() signals are delivered to the main thread.
    // prosessEvents() should empty the pending queue.
    qApp->processEvents();

    QCOMPARE(startedCount, 1);
    QCOMPARE(finishedCount, 1);
}

void mapSleeper(int &)
{
    QTest::qSleep(100);
}

static QSet<int> progressValues;
static QSet<QString> progressTexts;
static QMutex mutex;
class ProgressObject : public QObject
{
Q_OBJECT
public slots:
    void printProgress(int);
    void printText(const QString &text);
    void registerProgress(int);
    void registerText(const QString &text);
};

void ProgressObject::printProgress(int progress)
{
    qDebug() << "thread" << QThread::currentThread() << "reports progress" << progress;
}

void ProgressObject::printText(const QString &text)
{
    qDebug() << "thread" << QThread::currentThread() << "reports progress text" << text;
}

void ProgressObject::registerProgress(int progress)
{
    QTest::qSleep(1);
    progressValues.insert(progress);
}

void ProgressObject::registerText(const QString &text)
{
    QTest::qSleep(1);
    progressTexts.insert(text);
}


QList<int> createList(int listSize)
{
    QList<int> list;
    for (int i = 0; i < listSize; ++i) {
        list.append(i);
    }
    return list;
}

void tst_QFutureWatcher::progressValueChanged()
{
#ifdef PRINT
    qDebug() << "main thread" << QThread::currentThread();
#endif

    progressValues.clear();
    const int listSize = 20;
    QList<int> list = createList(listSize);

    QFutureWatcher<void> futureWatcher;
    ProgressObject progressObject;
    QObject::connect(&futureWatcher, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
#ifdef PRINT
    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &progressObject, SLOT(printProgress(int)), Qt::DirectConnection );
#endif
    QObject::connect(&futureWatcher, SIGNAL(progressValueChanged(int)), &progressObject, SLOT(registerProgress(int)));

    futureWatcher.setFuture(QtConcurrent::map(list, mapSleeper));

    QTestEventLoop::instance().enterLoop(5);
    QVERIFY(!QTestEventLoop::instance().timeout());
    futureWatcher.disconnect();
    QVERIFY(progressValues.contains(0));
    QVERIFY(progressValues.contains(listSize));
}

class CancelObject : public QObject
{
Q_OBJECT
public:
    bool wasCanceled;
    CancelObject() : wasCanceled(false) {}
public slots:
    void cancel();
};

void CancelObject::cancel()
{
#ifdef PRINT
    qDebug() << "thread" << QThread::currentThread() << "reports canceled";
#endif
    wasCanceled = true;
}

void tst_QFutureWatcher::canceled()
{
    const int listSize = 20;
    QList<int> list = createList(listSize);

    QFutureWatcher<void> futureWatcher;
    QFuture<void> future;
    CancelObject cancelObject;

    QObject::connect(&futureWatcher, SIGNAL(canceled()), &cancelObject, SLOT(cancel()));
    QObject::connect(&futureWatcher, SIGNAL(canceled()),
        &QTestEventLoop::instance(), SLOT(exitLoop()), Qt::QueuedConnection);

    future = QtConcurrent::map(list, mapSleeper);
    futureWatcher.setFuture(future);
    futureWatcher.cancel();
    QTestEventLoop::instance().enterLoop(5);
    QVERIFY(!QTestEventLoop::instance().timeout());

    QVERIFY(future.isCanceled());
    QVERIFY(cancelObject.wasCanceled);
    futureWatcher.disconnect();
    future.waitForFinished();
}

void tst_QFutureWatcher::cancelAndFinish_data()
{
    QTest::addColumn<bool>("isCanceled");
    QTest::addColumn<bool>("isFinished");

    QTest::addRow("running") << false << false;
    QTest::addRow("canceled") << true << false;
    QTest::addRow("finished") << false << true;
    QTest::addRow("canceledAndFinished") << true << true;
}

void tst_QFutureWatcher::cancelAndFinish()
{
    QFETCH(bool, isCanceled);
    QFETCH(bool, isFinished);

    QFutureInterface<void> fi;
    QFutureWatcher<void> futureWatcher;
    QSignalSpy finishedSpy(&futureWatcher, &QFutureWatcher<void>::finished);
    QSignalSpy canceledSpy(&futureWatcher, &QFutureWatcher<void>::canceled);
    futureWatcher.setFuture(fi.future());

    fi.reportStarted();

    if (isCanceled)
        fi.cancel();
    if (isFinished)
        fi.reportFinished();

    fi.cancelAndFinish();

    // The signals should be emitted only once
    QTRY_COMPARE(canceledSpy.size(), 1);
    QTRY_COMPARE(finishedSpy.size(), 1);
}

class IntTask : public RunFunctionTaskBase<int>
{
public:
    void runFunctor() override
    {
        promise.reportResult(10);
    }
};

void tst_QFutureWatcher::resultAt()
{
    QFutureWatcher<int> futureWatcher;
    futureWatcher.setFuture((new IntTask())->start());
    futureWatcher.waitForFinished();
    QCOMPARE(futureWatcher.result(), 10);
    QCOMPARE(futureWatcher.resultAt(0), 10);
}

void tst_QFutureWatcher::resultReadyAt()
{
    QFutureWatcher<int> futureWatcher;
    QSignalSpy resultSpy(&futureWatcher, &QFutureWatcher<int>::resultReadyAt);

    QFuture<int> future = (new IntTask())->start();
    futureWatcher.setFuture(future);

    QVERIFY(resultSpy.wait());

    // Setting the future again should give us another signal.
    // (this is to prevent the race where the task associated
    // with the future finishes before setFuture is called.)
    futureWatcher.setFuture(QFuture<int>());
    futureWatcher.setFuture(future);

    QVERIFY(resultSpy.wait());
}

void tst_QFutureWatcher::orderedResultReadyAt()
{
    for (int i = 0; i < 1000; ++i) {
        QObject context;
        QFuture<QString> f = run([](QPromise<QString> &fi) {
            fi.addResult("First");
            fi.addResult("Second");
        });
        QList<int> actualIndices;

        QFutureWatcher<QString> watcher;
        connect(&watcher, &QFutureWatcherBase::resultReadyAt, &context,
                [&actualIndices](int index) { actualIndices.append(index); });
        watcher.setFuture(f);
        f.waitForFinished();
        QCoreApplication::processEvents();
        const QList<int> expectedIndices{0, 1};
        QCOMPARE(actualIndices.size(), expectedIndices.size());
        QCOMPARE(actualIndices, expectedIndices);
    }
}

class SignalSlotObject : public QObject
{
Q_OBJECT

signals:
    void cancel();

public slots:
    void started()
    {
        qDebug() << "started called";
    }

    void finished()
    {
        qDebug() << "finished called";
    }

    void canceled()
    {
        qDebug() << "canceled called";
    }

#ifdef PRINT
    void resultReadyAt(int index)
    {
        qDebug() << "result" << index << "ready";
    }
#else
    void resultReadyAt(int) { }
#endif
    void progressValueChanged(int progress)
    {
        qDebug() << "progress" << progress;
    }

    void progressRangeChanged(int min, int max)
    {
        qDebug() << "progress range" << min << max;
    }

};

void tst_QFutureWatcher::futureSignals()
{
    {
        QFutureInterface<int> a;
        QFutureWatcher<int> f;

        SignalSlotObject object;
#ifdef PRINT
        connect(&f, SIGNAL(finished()), &object, SLOT(finished()));
        connect(&f, SIGNAL(progressValueChanged(int)), &object, SLOT(progressValueChanged(int)));
#endif
        // must connect to resultReadyAt so that the watcher can detect the connection
        // (QSignalSpy does not trigger it.)
        connect(&f, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
        a.reportStarted();

        QSignalSpy progressSpy(&f, &QFutureWatcher<void>::progressValueChanged);
        QSignalSpy finishedSpy(&f, &QFutureWatcher<void>::finished);
        QSignalSpy resultReadySpy(&f, &QFutureWatcher<void>::resultReadyAt);

        QVERIFY(progressSpy.isValid());
        QVERIFY(finishedSpy.isValid());
        QVERIFY(resultReadySpy.isValid());
        f.setFuture(a.future());

        const int progress = 1;
        a.setProgressValue(progress);
        QTRY_COMPARE(progressSpy.size(), 2);
        QCOMPARE(progressSpy.takeFirst().at(0).toInt(), 0);
        QCOMPARE(progressSpy.takeFirst().at(0).toInt(), 1);

        const int result = 10;
        a.reportResult(&result);
        QVERIFY(resultReadySpy.wait());
        QCOMPARE(resultReadySpy.size(), 1);
        a.reportFinished(&result);

        QTRY_COMPARE(resultReadySpy.size(), 2);
        QCOMPARE(resultReadySpy.takeFirst().at(0).toInt(), 0); // check the index
        QCOMPARE(resultReadySpy.takeFirst().at(0).toInt(), 1);

        QCOMPARE(finishedSpy.size(), 1);
    }
}

void tst_QFutureWatcher::watchFinishedFuture()
{
    QFutureInterface<int> iface;
    iface.reportStarted();

    QFuture<int> f = iface.future();

    int value = 100;
    iface.reportFinished(&value);

    QFutureWatcher<int> watcher;

    SignalSlotObject object;
#ifdef PRINT
    connect(&watcher, SIGNAL(started()), &object, SLOT(started()));
    connect(&watcher, SIGNAL(canceled()), &object, SLOT(canceled()));
    connect(&watcher, SIGNAL(finished()), &object, SLOT(finished()));
    connect(&watcher, SIGNAL(progressValueChanged(int)), &object, SLOT(progressValueChanged(int)));
    connect(&watcher, SIGNAL(progressRangeChanged(int,int)), &object, SLOT(progressRangeChanged(int,int)));
#endif
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));

    QSignalSpy startedSpy(&watcher, &QFutureWatcher<int>::started);
    QSignalSpy finishedSpy(&watcher, &QFutureWatcher<int>::finished);
    QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
    QSignalSpy canceledSpy(&watcher, &QFutureWatcher<int>::canceled);

    QVERIFY(startedSpy.isValid());
    QVERIFY(finishedSpy.isValid());
    QVERIFY(resultReadySpy.isValid());
    QVERIFY(canceledSpy.isValid());

    watcher.setFuture(f);
    QVERIFY(finishedSpy.wait());

    QCOMPARE(startedSpy.size(), 1);
    QCOMPARE(finishedSpy.size(), 1);
    QCOMPARE(resultReadySpy.size(), 1);
    QCOMPARE(canceledSpy.size(), 0);
}

void tst_QFutureWatcher::watchCanceledFuture()
{
    QFuture<int> f;
    QFutureWatcher<int> watcher;

    SignalSlotObject object;
#ifdef PRINT
    connect(&watcher, SIGNAL(started()), &object, SLOT(started()));
    connect(&watcher, SIGNAL(canceled()), &object, SLOT(canceled()));
    connect(&watcher, SIGNAL(finished()), &object, SLOT(finished()));
    connect(&watcher, SIGNAL(progressValueChanged(int)), &object, SLOT(progressValueChanged(int)));
    connect(&watcher, SIGNAL(progressRangeChanged(int,int)), &object, SLOT(progressRangeChanged(int,int)));
#endif
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));

    QSignalSpy startedSpy(&watcher, &QFutureWatcher<int>::started);
    QSignalSpy finishedSpy(&watcher, &QFutureWatcher<int>::finished);
    QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
    QSignalSpy canceledSpy(&watcher, &QFutureWatcher<int>::canceled);

    QVERIFY(startedSpy.isValid());
    QVERIFY(finishedSpy.isValid());
    QVERIFY(resultReadySpy.isValid());
    QVERIFY(canceledSpy.isValid());

    watcher.setFuture(f);
    QVERIFY(finishedSpy.wait());

    QCOMPARE(startedSpy.size(), 1);
    QCOMPARE(finishedSpy.size(), 1);
    QCOMPARE(resultReadySpy.size(), 0);
    QCOMPARE(canceledSpy.size(), 1);
}

void tst_QFutureWatcher::disconnectRunningFuture()
{
    QFutureInterface<int> a;
    a.reportStarted();

    QFuture<int> f = a.future();
    QFutureWatcher<int> *watcher = new QFutureWatcher<int>();
    QSignalSpy finishedSpy(watcher, &QFutureWatcher<int>::finished);
    QSignalSpy resultReadySpy(watcher, &QFutureWatcher<int>::resultReadyAt);

    QVERIFY(finishedSpy.isValid());
    QVERIFY(resultReadySpy.isValid());
    watcher->setFuture(f);

    SignalSlotObject object;
    connect(watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));

    const int result = 10;
    a.reportResult(&result);
    QVERIFY(resultReadySpy.wait());
    QCOMPARE(resultReadySpy.size(), 1);

    delete watcher;

    a.reportResult(&result);
    QTest::qWait(10);
    QCOMPARE(resultReadySpy.size(), 1);

    a.reportFinished(&result);
    QTest::qWait(10);
    QCOMPARE(finishedSpy.size(), 0);
}

const int maxProgress = 100000;
class ProgressEmitterTask : public RunFunctionTaskBase<void>
{
public:
    void runFunctor() override
    {
        promise.setProgressRange(0, maxProgress);
        for (int p = 0; p <= maxProgress; ++p)
            promise.setProgressValue(p);
    }
};

void tst_QFutureWatcher::tooMuchProgress()
{
    progressValues.clear();
    ProgressObject o;

    QFutureWatcher<void> f;
    QObject::connect(&f, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
#ifdef PRINT
    QObject::connect(&f, SIGNAL(progressValueChanged(int)), &o, SLOT(printProgress(int)));
#endif
    QObject::connect(&f, SIGNAL(progressValueChanged(int)), &o, SLOT(registerProgress(int)));
    f.setFuture((new ProgressEmitterTask())->start());

    // Android reports ca. 10k progressValueChanged per second
    QTestEventLoop::instance().enterLoop(15);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QVERIFY(progressValues.contains(maxProgress));
}

template <typename T>
class ProgressTextTask : public RunFunctionTaskBase<T>
{
public:
    void runFunctor() override
    {
        this->promise.setProgressValueAndText(1, QLatin1String("Foo 1"));

        while (this->promise.isProgressUpdateNeeded() == false)
            QTest::qSleep(1);
        this->promise.setProgressValueAndText(2, QLatin1String("Foo 2"));

        while (this->promise.isProgressUpdateNeeded() == false)
            QTest::qSleep(1);
        this->promise.setProgressValueAndText(3, QLatin1String("Foo 3"));

        while (this->promise.isProgressUpdateNeeded() == false)
            QTest::qSleep(1);
        this->promise.setProgressValueAndText(4, QLatin1String("Foo 4"));
    }
};

void tst_QFutureWatcher::progressText()
{
    {   // instantiate API for T=int and T=void.
        ProgressTextTask<int> a;
        ProgressTextTask<void> b;
    }
    {
        progressValues.clear();
        progressTexts.clear();
        QFuture<int> f = ((new ProgressTextTask<int>())->start());
        QFutureWatcher<int> watcher;
        ProgressObject o;
        QObject::connect(&watcher, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));
#ifdef PRINT
        QObject::connect(&watcher, SIGNAL(progressValueChanged(int)), &o, SLOT(printProgress(int)));
        QObject::connect(&watcher, SIGNAL(progressTextChanged(QString)), &o, SLOT(printText(QString)));
#endif
        QObject::connect(&watcher, SIGNAL(progressValueChanged(int)), &o, SLOT(registerProgress(int)));
        QObject::connect(&watcher, SIGNAL(progressTextChanged(QString)), &o, SLOT(registerText(QString)));

        watcher.setFuture(f);
        QTestEventLoop::instance().enterLoop(5);
        QVERIFY(!QTestEventLoop::instance().timeout());

        QCOMPARE(f.progressText(), QLatin1String("Foo 4"));
        QCOMPARE(f.progressValue(), 4);
        QVERIFY(progressValues.contains(1));
        QVERIFY(progressValues.contains(2));
        QVERIFY(progressValues.contains(3));
        QVERIFY(progressValues.contains(4));
        QVERIFY(progressTexts.contains(QLatin1String("Foo 1")));
        QVERIFY(progressTexts.contains(QLatin1String("Foo 2")));
        QVERIFY(progressTexts.contains(QLatin1String("Foo 3")));
        QVERIFY(progressTexts.contains(QLatin1String("Foo 4")));
    }
}

template <typename T>
void callInterface(T &obj)
{
    obj.progressValue();
    obj.progressMinimum();
    obj.progressMaximum();
    obj.progressText();

    obj.isStarted();
    obj.isFinished();
    obj.isRunning();
    obj.isCanceled();
    obj.isSuspended();
    obj.isSuspending();

    obj.cancel();
    obj.suspend();
    obj.resume();
    obj.toggleSuspended();
#if QT_DEPRECATED_SINCE(6, 0)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
    obj.isPaused();
    obj.pause();
    obj.togglePaused();
QT_WARNING_POP
#endif
    obj.waitForFinished();

    const T& objConst = obj;
    objConst.progressValue();
    objConst.progressMinimum();
    objConst.progressMaximum();
    objConst.progressText();

    objConst.isStarted();
    objConst.isFinished();
    objConst.isRunning();
    objConst.isCanceled();
    objConst.isSuspending();
    objConst.isSuspended();
#if QT_DEPRECATED_SINCE(6, 0)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
    objConst.isPaused();
QT_WARNING_POP
#endif
}

template <typename T>
void callInterface(const T &obj)
{
    obj.result();
    obj.resultAt(0);
}


// QFutureWatcher and QFuture has a similar interface. Test
// that the functions we want ot have in both are actually
// there.
void tst_QFutureWatcher::sharedFutureInterface()
{
    QFutureInterface<int> iface;
    iface.reportStarted();

    QFuture<int> intFuture = iface.future();

    int value = 0;
    iface.reportFinished(&value);

    QFuture<void> voidFuture;
    QFutureWatcher<int> intWatcher;
    intWatcher.setFuture(intFuture);
    QFutureWatcher<void> voidWatcher;

    callInterface(intFuture);
    callInterface(voidFuture);
    callInterface(intWatcher);
    callInterface(voidWatcher);

    callInterface(intFuture);
    callInterface(intWatcher);
}

void tst_QFutureWatcher::changeFuture()
{
    QFutureInterface<int> iface;
    iface.reportStarted();

    QFuture<int> a = iface.future();

    int value = 0;
    iface.reportFinished(&value);

    QFuture<int> b;

    QFutureWatcher<int> watcher;

    SignalSlotObject object;
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
    QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
    QVERIFY(resultReadySpy.isValid());

    watcher.setFuture(a); // Watch 'a' which will generate a resultReady event.
    watcher.setFuture(b); // But oh no! we're switching to another future
    QTest::qWait(10);     // before the event gets delivered.

    QCOMPARE(resultReadySpy.size(), 0);

    watcher.setFuture(a);
    watcher.setFuture(b);
    watcher.setFuture(a); // setting it back gets us one event, not two.
    QVERIFY(resultReadySpy.wait());

    QCOMPARE(resultReadySpy.size(), 1);
}

// Test that events aren't delivered from canceled futures
void tst_QFutureWatcher::cancelEvents()
{
    QFutureInterface<int> iface;
    iface.reportStarted();

    QFuture<int> a = iface.future();

    int value = 0;
    iface.reportFinished(&value);

    QFutureWatcher<int> watcher;

    SignalSlotObject object;
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
    QSignalSpy finishedSpy(&watcher, &QFutureWatcher<int>::finished);
    QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
    QVERIFY(finishedSpy.isValid());
    QVERIFY(resultReadySpy.isValid());

    watcher.setFuture(a);
    watcher.cancel();

    QVERIFY(finishedSpy.wait());

    QCOMPARE(resultReadySpy.size(), 0);
}

#if QT_DEPRECATED_SINCE(6, 0)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
// Tests that events from paused futures are saved and
// delivered on resume.
void tst_QFutureWatcher::pauseEvents()
{
    {
        QFutureInterface<int> iface;
        iface.reportStarted();

        QFutureWatcher<int> watcher;

        SignalSlotObject object;
        connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
        QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
        QVERIFY(resultReadySpy.isValid());

        QSignalSpy pauseSpy(&watcher, &QFutureWatcher<int>::paused);
        QVERIFY(pauseSpy.isValid());

        watcher.setFuture(iface.future());
        watcher.pause();

        QTRY_COMPARE(pauseSpy.size(), 1);

        int value = 0;
        iface.reportFinished(&value);

        // A result is reported, although the watcher is paused.
        // The corresponding event should be also reported.
        QTRY_COMPARE(resultReadySpy.size(), 1);

        watcher.resume();
    }
    {
        QFutureInterface<int> iface;
        iface.reportStarted();

        QFuture<int> a = iface.future();

        QFutureWatcher<int> watcher;

        SignalSlotObject object;
        connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
        QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
        QVERIFY(resultReadySpy.isValid());

        watcher.setFuture(a);
        a.pause();

        int value = 0;
        iface.reportFinished(&value);

        QFuture<int> b;
        watcher.setFuture(b); // If we watch b instead, resuming a
        a.resume();           // should give us no results.

        QTest::qWait(10);
        QCOMPARE(resultReadySpy.size(), 0);
    }
}

void tst_QFutureWatcher::pausedSuspendedOrder()
{
    QFutureInterface<void> iface;
    iface.reportStarted();

    QFutureWatcher<void> watcher;

    QSignalSpy pausedSpy(&watcher, &QFutureWatcher<void>::paused);
    QVERIFY(pausedSpy.isValid());

    QSignalSpy suspendedSpy(&watcher, &QFutureWatcher<void>::suspended);
    QVERIFY(suspendedSpy.isValid());

    bool pausedBeforeSuspended = false;
    bool notSuspendedBeforePaused = false;
    connect(&watcher, &QFutureWatcher<void>::paused,
            [&] { notSuspendedBeforePaused = (suspendedSpy.size() == 0); });
    connect(&watcher, &QFutureWatcher<void>::suspended,
            [&] { pausedBeforeSuspended = (pausedSpy.size() == 1); });

    watcher.setFuture(iface.future());
    iface.reportSuspended();

    // Make sure reportPaused() is ignored if the state is not paused
    pausedSpy.wait(100);
    QCOMPARE(pausedSpy.size(), 0);
    QCOMPARE(suspendedSpy.size(), 0);

    iface.setPaused(true);
    iface.reportSuspended();

    QTRY_COMPARE(suspendedSpy.size(), 1);
    QCOMPARE(pausedSpy.size(), 1);
    QVERIFY(notSuspendedBeforePaused);
    QVERIFY(pausedBeforeSuspended);

    iface.reportFinished();
}
QT_WARNING_POP
#endif // QT_DEPRECATED_SINCE(6, 0)

// Tests that events from suspended futures are saved and
// delivered on resume.
void tst_QFutureWatcher::suspendEvents()
{
    {
        QFutureInterface<int> iface;
        iface.reportStarted();

        QFutureWatcher<int> watcher;

        SignalSlotObject object;
        connect(&watcher, &QFutureWatcher<int>::resultReadyAt, &object,
                &SignalSlotObject::resultReadyAt);
        QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
        QVERIFY(resultReadySpy.isValid());

        QSignalSpy suspendingSpy(&watcher, &QFutureWatcher<int>::suspending);
        QVERIFY(suspendingSpy.isValid());

        watcher.setFuture(iface.future());
        watcher.suspend();

        QTRY_COMPARE(suspendingSpy.size(), 1);

        int value = 0;
        iface.reportFinished(&value);

        // A result is reported, although the watcher is paused.
        // The corresponding event should be also reported.
        QTRY_COMPARE(resultReadySpy.size(), 1);

        watcher.resume();
    }
    {
        QFutureInterface<int> iface;
        iface.reportStarted();

        QFuture<int> a = iface.future();

        QFutureWatcher<int> watcher;

        SignalSlotObject object;
        connect(&watcher, &QFutureWatcher<int>::resultReadyAt, &object,
                &SignalSlotObject::resultReadyAt);
        QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
        QVERIFY(resultReadySpy.isValid());

        watcher.setFuture(a);
        a.suspend();

        int value = 0;
        iface.reportFinished(&value);

        QFuture<int> b;
        watcher.setFuture(b); // If we watch b instead, resuming a
        a.resume();           // should give us no results.

        QTest::qWait(10);
        QCOMPARE(resultReadySpy.size(), 0);
    }
}

void tst_QFutureWatcher::suspended()
{
    QFutureWatcher<int> watcher;
    QSignalSpy resultReadySpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
#if QT_DEPRECATED_SINCE(6, 0)
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
    QSignalSpy pausedSpy(&watcher, &QFutureWatcher<int>::paused);
QT_WARNING_POP
#endif
    QSignalSpy suspendingSpy(&watcher, &QFutureWatcher<int>::suspending);
    QSignalSpy suspendedSpy(&watcher, &QFutureWatcher<int>::suspended);
    QSignalSpy finishedSpy(&watcher, &QFutureWatcher<int>::finished);

    const int numValues = 25;
    std::vector<int> values(numValues, 0);
    std::atomic_int count = 0;

    QThreadPool pool;
    pool.setMaxThreadCount(3);

    QFuture<int> future = QtConcurrent::mapped(&pool, values, [&](int value) {
        ++count;
        // Sleep, to make sure not all threads will start at once.
        QThread::sleep(50ms);
        return value;
    });
    watcher.setFuture(future);

    // Allow some threads to start before suspending.
    QThread::sleep(200ms);

    watcher.suspend();
    watcher.suspend();
    QTRY_COMPARE(suspendedSpy.size(), 1); // suspended() should be emitted only once
    QCOMPARE(suspendingSpy.size(), 2); // suspending() is emitted as many times as requested
#if QT_DEPRECATED_SINCE(6, 0)
    QCOMPARE(pausedSpy.size(), 2); // paused() is emitted as many times as requested
#endif

    // Make sure QFutureWatcher::resultReadyAt() is emitted only for already started threads.
    const auto resultReadyAfterPaused = resultReadySpy.size();
    QCOMPARE(resultReadyAfterPaused, count);

    // Make sure no more results are reported before resuming.
    QThread::sleep(200ms);
    QCOMPARE(resultReadyAfterPaused, resultReadySpy.size());
    resultReadySpy.clear();

    watcher.resume();
    QTRY_COMPARE(finishedSpy.size(), 1);

    // Make sure that no more suspended() signals have been emitted.
    QCOMPARE(suspendedSpy.size(), 1);

    // Make sure the rest of results were reported after resume.
    QCOMPARE(resultReadySpy.size(), numValues - resultReadyAfterPaused);
}

void tst_QFutureWatcher::suspendedEventsOrder()
{
    QFutureInterface<void> iface;
    iface.reportStarted();

    QFutureWatcher<void> watcher;

    QSignalSpy suspendingSpy(&watcher, &QFutureWatcher<void>::suspending);
    QVERIFY(suspendingSpy.isValid());

    QSignalSpy suspendedSpy(&watcher, &QFutureWatcher<void>::suspended);
    QVERIFY(suspendedSpy.isValid());

    bool suspendingBeforeSuspended = false;
    bool notSuspendedBeforeSuspending = false;
    connect(&watcher, &QFutureWatcher<void>::suspending,
            [&] { notSuspendedBeforeSuspending = (suspendedSpy.size() == 0); });
    connect(&watcher, &QFutureWatcher<void>::suspended,
            [&] { suspendingBeforeSuspended = (suspendingSpy.size() == 1); });

    watcher.setFuture(iface.future());
    iface.reportSuspended();

    // Make sure reportPaused() is ignored if the state is not paused
    suspendingSpy.wait(100);
    QCOMPARE(suspendingSpy.size(), 0);
    QCOMPARE(suspendedSpy.size(), 0);

    iface.setSuspended(true);
    iface.reportSuspended();

    QTRY_COMPARE(suspendedSpy.size(), 1);
    QCOMPARE(suspendingSpy.size(), 1);
    QVERIFY(notSuspendedBeforeSuspending);
    QVERIFY(suspendingBeforeSuspended);

    iface.reportFinished();
}

/*
    Verify that throttling kicks in if you report a lot of results,
    and that it clears when the result events are processed.
*/
void tst_QFutureWatcher::throttling()
{
    QFutureInterface<int> iface;
    iface.reportStarted();
    QFuture<int> future = iface.future();
    QFutureWatcher<int> watcher;
    QSignalSpy resultSpy(&watcher, &QFutureWatcher<int>::resultReadyAt);
    watcher.setFuture(future);

    QVERIFY(!iface.isThrottled());

    const int resultCount = 1000;
    for (int i = 0; i < resultCount; ++i) {
        int result = 0;
        iface.reportResult(result);
    }

    QVERIFY(iface.isThrottled());

    QTRY_COMPARE(resultSpy.size(), resultCount); // Process the results

    QVERIFY(!iface.isThrottled());

    iface.reportFinished();
}

int mapper(const int &i)
{
    return i;
}

class ResultReadyTester : public QObject
{
Q_OBJECT
public:
    ResultReadyTester(QFutureWatcher<int> *watcher)
    :m_watcher(watcher), filter(false), ok(true), count(0)
    {

    }
public slots:
    void resultReadyAt(int index)
    {
        ++count;
        if (m_watcher->future().isResultReadyAt(index) == false)
            ok = false;
        if (!filter && m_watcher->future().resultAt(index) != index)
            ok = false;
        if (filter && m_watcher->future().resultAt(index) != index * 2 + 1)
            ok = false;
    }
public:
    QFutureWatcher<int> *m_watcher;
    bool filter;
    bool ok;
    int count;
};

void tst_QFutureWatcher::incrementalMapResults()
{
    QFutureWatcher<int> watcher;

    SignalSlotObject object;
#ifdef PRINT
    connect(&watcher, SIGNAL(finished()), &object, SLOT(finished()));
    connect(&watcher, SIGNAL(progressValueChanged(int)), &object, SLOT(progressValueChanged(int)));
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
#endif

    QObject::connect(&watcher, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));

    ResultReadyTester resultReadyTester(&watcher);
    connect(&watcher, SIGNAL(resultReadyAt(int)), &resultReadyTester, SLOT(resultReadyAt(int)));

    const int count = 10000;
    QList<int> ints;
    for (int i = 0; i < count; ++i)
        ints << i;

    QFuture<int> future = QtConcurrent::mapped(ints, mapper);
    watcher.setFuture(future);

    QTestEventLoop::instance().enterLoop(10);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QCOMPARE(resultReadyTester.count, count);
    QVERIFY(resultReadyTester.ok);
    QVERIFY(watcher.isFinished());
    future.waitForFinished();
}

bool filterer(int i)
{
    return (i % 2);
}

void tst_QFutureWatcher::incrementalFilterResults()
{
    QFutureWatcher<int> watcher;

    SignalSlotObject object;
#ifdef PRINT
    connect(&watcher, SIGNAL(finished()), &object, SLOT(finished()));
    connect(&watcher, SIGNAL(progressValueChanged(int)), &object, SLOT(progressValueChanged(int)));
    connect(&watcher, SIGNAL(resultReadyAt(int)), &object, SLOT(resultReadyAt(int)));
#endif

    QObject::connect(&watcher, SIGNAL(finished()), &QTestEventLoop::instance(), SLOT(exitLoop()));


    ResultReadyTester resultReadyTester(&watcher);
    resultReadyTester.filter = true;
    connect(&watcher, SIGNAL(resultReadyAt(int)), &resultReadyTester, SLOT(resultReadyAt(int)));

    const int count = 10000;
    QList<int> ints;
    for (int i = 0; i < count; ++i)
        ints << i;

    QFuture<int> future = QtConcurrent::filtered(ints, filterer);
    watcher.setFuture(future);

    QTestEventLoop::instance().enterLoop(10);
    QVERIFY(!QTestEventLoop::instance().timeout());
    QCOMPARE(resultReadyTester.count, count / 2);
    QVERIFY(resultReadyTester.ok);
    QVERIFY(watcher.isFinished());
    future.waitForFinished();
}

void tst_QFutureWatcher::qfutureSynchronizer()
{
    int taskCount = 1000;
    QElapsedTimer t;
    t.start();

    {
        QFutureSynchronizer<void> sync;

        sync.setCancelOnWait(true);
        for (int i = 0; i < taskCount; ++i) {
            sync.addFuture(run(sleeper));
        }
    }

    // Test that we're not running each task.
    QVERIFY(t.elapsed() < taskCount * 10);
}

class DummyObject : public QObject {
    Q_OBJECT
public slots:
    void dummySlot() {}
public:
    static void function(QMutex *m)
    {
        QMutexLocker lock(m);
    }
};

void tst_QFutureWatcher::warnRace()
{
#ifndef Q_OS_DARWIN // I don't know why it is not working on mac
#ifndef QT_NO_DEBUG
    QTest::ignoreMessage(QtWarningMsg, "QFutureWatcher::connect: connecting after calling setFuture() is likely to produce race");
#endif
#endif
    QFutureWatcher<void> watcher;
    DummyObject object;
    QMutex mutex;
    mutex.lock();

    QFuture<void> future = QtConcurrent::run(DummyObject::function, &mutex);
    watcher.setFuture(future);
    QTRY_VERIFY(future.isStarted());
    connect(&watcher, SIGNAL(finished()), &object, SLOT(dummySlot()));
    mutex.unlock();
    future.waitForFinished();
}

void tst_QFutureWatcher::matchFlags()
{
    /* Regression test: expect a default watcher to be in the same state as a
     * default future. */
    QFutureWatcher<int> watcher;
    QFuture<int> future;
    QCOMPARE(watcher.isStarted(), future.isStarted());
    QCOMPARE(watcher.isCanceled(), future.isCanceled());
    QCOMPARE(watcher.isFinished(), future.isFinished());
}

void tst_QFutureWatcher::checkStateConsistency()
{
#define CHECK_FAIL(state)                                                                          \
    do {                                                                                           \
        if (QTest::currentTestFailed())                                                            \
            QFAIL("checkState() failed, QFutureWatcher has inconistent state after " state "!");   \
    } while (false)

    QFutureWatcher<void> futureWatcher;

    auto checkState = [&futureWatcher] {
        QCOMPARE(futureWatcher.isStarted(), futureWatcher.future().isStarted());
        QCOMPARE(futureWatcher.isRunning(), futureWatcher.future().isRunning());
        QCOMPARE(futureWatcher.isCanceled(), futureWatcher.future().isCanceled());
        QCOMPARE(futureWatcher.isSuspended(), futureWatcher.future().isSuspended());
        QCOMPARE(futureWatcher.isSuspending(), futureWatcher.future().isSuspending());
        QCOMPARE(futureWatcher.isFinished(), futureWatcher.future().isFinished());
    };

    checkState();
    CHECK_FAIL("default-constructing");

    QFutureInterface<void> fi;
    futureWatcher.setFuture(fi.future());
    checkState();
    CHECK_FAIL("setting future");

    fi.reportStarted();
    checkState();
    CHECK_FAIL("starting");

    fi.future().suspend();
    checkState();
    CHECK_FAIL("suspending");

    fi.reportSuspended();
    checkState();
    CHECK_FAIL("suspended");

    fi.reportCanceled();
    checkState();
    CHECK_FAIL("canceling");

    fi.reportFinished();
    checkState();
    CHECK_FAIL("finishing");

#undef CHECK_FAIL
}

QTEST_MAIN(tst_QFutureWatcher)
#include "tst_qfuturewatcher.moc"