File: kdirlistertest.cpp

package info (click to toggle)
kio 5.116.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 41,496 kB
  • sloc: cpp: 123,468; xml: 528; ansic: 466; ruby: 60; sh: 21; makefile: 13
file content (1791 lines) | stat: -rw-r--r-- 68,855 bytes parent folder | download | duplicates (2)
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
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
/*
    This file is part of the KDE project
    SPDX-FileCopyrightText: 2007 David Faure <faure@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "kdirlistertest.h"

#include "jobuidelegatefactory.h"
#include "kiotesthelper.h"
#include <kio/copyjob.h>
#include <kio/deletejob.h>
#include <kio/jobuidelegateextension.h>
#include <kio/simplejob.h>
#include <kprotocolinfo.h>

#include <KDirWatch>

#include <QDebug>
#include <QTemporaryFile>
#include <QTest>

QTEST_MAIN(KDirListerTest)

static constexpr bool s_workaroundBrokenInotify = false;

GlobalInits::GlobalInits()
{
    // Must be done before the QSignalSpys connect
    qRegisterMetaType<KFileItem>();
    qRegisterMetaType<KFileItemList>();
    qRegisterMetaType<KIO::Job *>();
}

QString KDirListerTest::tempPath() const
{
    return m_tempDir->path() + '/';
}

void KDirListerTest::initTestCase()
{
    // To avoid failing on broken locally defined MIME types
    QStandardPaths::setTestModeEnabled(true);

    m_tempDir.reset(new QTemporaryDir(homeTmpDir()));

    // No message dialogs
    KIO::setDefaultJobUiDelegateExtension(nullptr);
    KIO::setDefaultJobUiDelegateFactoryV2(nullptr);

    m_exitCount = 1;

    s_referenceTimeStamp = QDateTime::currentDateTime().addSecs(-120); // 2 minutes ago

    // Create test data:
    /*
     * PATH/toplevelfile_1
     * PATH/toplevelfile_2
     * PATH/toplevelfile_3
     * PATH/subdir
     * PATH/subdir/testfile
     * PATH/subdir/subsubdir
     * PATH/subdir/subsubdir/testfile
     */
    createTestFile(tempPath() + "toplevelfile_1");
    createTestFile(tempPath() + "toplevelfile_2");
    createTestFile(tempPath() + "toplevelfile_3");
    createTestDirectory(tempPath() + "subdir");
    createTestDirectory(tempPath() + "subdir/subsubdir");

    qRegisterMetaType<QList<QPair<KFileItem, KFileItem>>>();
}

void KDirListerTest::cleanup()
{
    m_dirLister.clearSpies();
    disconnect(&m_dirLister, nullptr, this, nullptr);
}

void KDirListerTest::testInvalidUrl()
{
    m_dirLister.openUrl(QUrl(":/"), KDirLister::NoFlags);
    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QVERIFY(m_dirLister.spyJobError.wait());
    QCOMPARE(m_dirLister.spyJobError.at(0).at(0).value<KIO::Job *>()->error(), KIO::ERR_MALFORMED_URL);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QVERIFY(m_dirLister.isFinished());
}

void KDirListerTest::testNonListableUrl()
{
    m_dirLister.openUrl(QUrl("data:foo"), KDirLister::NoFlags);
    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QVERIFY(m_dirLister.spyJobError.wait());
    QCOMPARE(m_dirLister.spyJobError.at(0).at(0).value<KIO::Job *>()->error(), KIO::ERR_UNSUPPORTED_ACTION);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QVERIFY(m_dirLister.isFinished());
}

void KDirListerTest::testOpenUrl()
{
    m_items.clear();
    const QString path = tempPath();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    // The call to openUrl itself, emits started
    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);

    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_dirLister.spyRedirection.count(), 0);
    QCOMPARE(m_items.count(), 0);
    QVERIFY(!m_dirLister.isFinished());

    // then wait for completed
    qDebug("waiting for completed");
    QTRY_COMPARE(m_dirLister.spyStarted.count(), 1);
    QTRY_COMPARE(m_dirLister.spyCompleted.count(), 1);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_dirLister.spyRedirection.count(), 0);
    // qDebug() << m_items;
    // qDebug() << "In dir" << QDir(path).entryList( QDir::AllEntries | QDir::NoDotAndDotDot);
    QCOMPARE(m_items.count(), fileCount());
    QVERIFY(m_dirLister.isFinished());
    disconnect(&m_dirLister, nullptr, this, nullptr);

    const QString fileName = QStringLiteral("toplevelfile_3");
    const QUrl itemUrl = QUrl::fromLocalFile(path + fileName);
    KFileItem byName = m_dirLister.findByName(fileName);
    QVERIFY(!byName.isNull());
    QCOMPARE(byName.url().toString(), itemUrl.toString());
    QCOMPARE(byName.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);
    KFileItem byUrl = m_dirLister.findByUrl(itemUrl);
    QVERIFY(!byUrl.isNull());
    QCOMPARE(byUrl.url().toString(), itemUrl.toString());
    QCOMPARE(byUrl.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);
    KFileItem itemForUrl = KDirLister::cachedItemForUrl(itemUrl);
    QVERIFY(!itemForUrl.isNull());
    QCOMPARE(itemForUrl.url().toString(), itemUrl.toString());
    QCOMPARE(itemForUrl.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);

    KFileItem rootByUrl = m_dirLister.findByUrl(QUrl::fromLocalFile(path));
    QVERIFY(!rootByUrl.isNull());
    QCOMPARE(QString(rootByUrl.url().toLocalFile() + '/'), path);

    m_dirLister.clearSpies(); // for the tests that call testOpenUrl for setup
}

// This test assumes testOpenUrl was run before. So m_dirLister is holding the items already.
void KDirListerTest::testOpenUrlFromCache()
{
    // Do the same again, it should behave the same, even with the items in the cache
    testOpenUrl();

    // Get into the case where another dirlister is holding the items
    {
        m_items.clear();
        const QString path = tempPath();
        MyDirLister secondDirLister;
        connect(&secondDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

        secondDirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
        QCOMPARE(secondDirLister.spyStarted.count(), 1);
        QCOMPARE(secondDirLister.spyCompleted.count(), 0);
        QCOMPARE(secondDirLister.spyCompletedQUrl.count(), 0);
        QCOMPARE(secondDirLister.spyCanceled.count(), 0);
        QCOMPARE(secondDirLister.spyCanceledQUrl.count(), 0);
        QCOMPARE(secondDirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
        QCOMPARE(secondDirLister.spyClearQUrl.count(), 0);
#endif
        QCOMPARE(secondDirLister.spyClearDir.count(), 0);

        QCOMPARE(m_items.count(), 0);
        QVERIFY(!secondDirLister.isFinished());

        // then wait for completed
        qDebug("waiting for completed");
        QTRY_COMPARE(secondDirLister.spyStarted.count(), 1);
        QTRY_COMPARE(secondDirLister.spyCompleted.count(), 1);
        QCOMPARE(secondDirLister.spyCompletedQUrl.count(), 1);
        QCOMPARE(secondDirLister.spyCanceled.count(), 0);
        QCOMPARE(secondDirLister.spyCanceledQUrl.count(), 0);
        QCOMPARE(secondDirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
        QCOMPARE(secondDirLister.spyClearQUrl.count(), 0);
#endif
        QCOMPARE(secondDirLister.spyClearDir.count(), 0);

        QCOMPARE(m_items.count(), 4);
        QVERIFY(secondDirLister.isFinished());
    }

    disconnect(&m_dirLister, nullptr, this, nullptr);
}

// This test assumes testOpenUrl was run before. So m_dirLister is holding the items already.
// This test creates 1 file in the temporary directory
void KDirListerTest::testNewItem()
{
    QCOMPARE(m_items.count(), 4);
    const QString path = tempPath();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    qDebug() << "Creating a new file";
    const QString fileName = QStringLiteral("toplevelfile_new");

    createSimpleFile(path + fileName);

    QTRY_COMPARE(m_items.count(), 5);
    QCOMPARE(m_dirLister.spyStarted.count(), 1); // Updates call started
    QCOMPARE(m_dirLister.spyCompleted.count(), 1); // and completed
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 0);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    const QUrl itemUrl = QUrl::fromLocalFile(path + fileName);
    KFileItem itemForUrl = KDirLister::cachedItemForUrl(itemUrl);
    QVERIFY(!itemForUrl.isNull());
    QCOMPARE(itemForUrl.url().toString(), itemUrl.toString());
    QCOMPARE(itemForUrl.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);
    disconnect(&m_dirLister, nullptr, this, nullptr);
}

// This test assumes testNewItem was run before. So m_dirLister is holding the items already.
// This test creates 100 more files in the temporary directory in reverse order
void KDirListerTest::testNewItems()
{
    QCOMPARE(m_items.count(), 5);
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    const QString path = tempPath();

    qDebug() << "Creating 100 new files";
    for (int i = 50; i > 0; i--) {
        createSimpleFile(path + QString("toplevelfile_new_%1").arg(i));
    }
    QTest::qWait(1000); // Create them with 1s difference
    for (int i = 100; i > 50; i--) {
        createSimpleFile(path + QString("toplevelfile_new_%1").arg(i));
    }

    // choose one of the new created files
    const QString fileName = QStringLiteral("toplevelfile_new_50");

    QTRY_COMPARE(m_items.count(), 105);

    QVERIFY(m_dirLister.spyStarted.count() > 0 && m_dirLister.spyStarted.count() < 3); // Updates call started, probably twice
    QVERIFY(m_dirLister.spyCompleted.count() > 0 && m_dirLister.spyCompleted.count() < 3); // and completed, probably twice
    QVERIFY(m_dirLister.spyCompletedQUrl.count() < 3);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 0);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    const QUrl itemUrl = QUrl::fromLocalFile(path + fileName);
    KFileItem itemForUrl = KDirLister::cachedItemForUrl(itemUrl);
    QVERIFY(!itemForUrl.isNull());
    QCOMPARE(itemForUrl.url().toString(), itemUrl.toString());
    QCOMPARE(itemForUrl.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);
}

void KDirListerTest::benchFindByUrl()
{
    // The time used should be in the order of O(100*log2(100))
    const QString path = tempPath();
    QBENCHMARK {
        for (int i = 100; i > 0; i--) {
            KFileItem cachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(path + QString("toplevelfile_new_%1").arg(i)));
            QVERIFY(!cachedItem.isNull());
        }
    }
}

void KDirListerTest::testNewItemByCopy()
{
    // This test creates a file using KIO::copyAs, like knewmenu.cpp does.
    // Useful for testing #192185, i.e. whether we catch the kdirwatch event and avoid
    // a KFileItem::refresh().
    const int origItemCount = m_items.count();
    const QString path = tempPath();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    QTest::qWait(1000); // We need a 1s timestamp difference on the dir, otherwise FAM won't notice anything.

    const QString fileName = QStringLiteral("toplevelfile_copy");
    const QUrl itemUrl = QUrl::fromLocalFile(path + fileName);
    KIO::CopyJob *job = KIO::copyAs(QUrl::fromLocalFile(path + "toplevelfile_3"), itemUrl, KIO::HideProgressInfo);
    job->exec();

    // Give time for KDirWatch/KDirNotify to notify us
    QTRY_COMPARE(m_items.count(), origItemCount + 1);

    QCOMPARE(m_dirLister.spyStarted.count(), 1); // Updates call started
    QCOMPARE(m_dirLister.spyCompleted.count(), 1); // and completed
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 0);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    // Give some time to KDirWatch
    QTest::qWait(1000);

    KFileItem itemForUrl = KDirLister::cachedItemForUrl(itemUrl);
    QVERIFY(!itemForUrl.isNull());
    QCOMPARE(itemForUrl.url().toString(), itemUrl.toString());
    QCOMPARE(itemForUrl.entry().stringValue(KIO::UDSEntry::UDS_NAME), fileName);
}

void KDirListerTest::testNewItemByCopyInSubDir() // #440712
{
    // Test that copying a file to a directory whose parent is listed
    // triggers refreshItems for the directory
    const int origItemCount = m_items.count();
    const QString path = tempPath();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    connect(&m_dirLister, &KDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems);
    QSignalSpy refreshItemSpy(this, &KDirListerTest::refreshItemsReceived);

    const QUrl subDirUrl = QUrl::fromLocalFile(path + "subdir");
    KFileItem itemForUrl = KDirLister::cachedItemForUrl(subDirUrl);
    auto origModificationDate = itemForUrl.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME);

    const QString fileName = path + "subdir/toplevelfile_copy";
    const QUrl itemUrl = QUrl::fromLocalFile(fileName);
    KIO::CopyJob *job = KIO::copyAs(QUrl::fromLocalFile(path + "toplevelfile_3"), itemUrl, KIO::HideProgressInfo);
    QVERIFY(job->exec());

    QTRY_COMPARE(m_items.count(), origItemCount);

    // Give some time to KDirNotify
    QVERIFY(refreshItemSpy.wait(100));

    itemForUrl = KDirLister::cachedItemForUrl(subDirUrl);
    QVERIFY(itemForUrl.entry().numberValue(KIO::UDSEntry::UDS_MODIFICATION_TIME) > origModificationDate);

    // clean leftover file
    QVERIFY(QFile(fileName).remove());
    m_refreshedItems.clear();
}

void KDirListerTest::testNewItemsInSymlink() // #213799
{
    const int origItemCount = m_items.count();
    QCOMPARE(fileCount(), origItemCount);
    const QString path = tempPath();
    QTemporaryFile tempFile;
    QVERIFY(tempFile.open());
    const QString symPath = tempFile.fileName() + "_link";
    tempFile.close();
    const bool symlinkOk = KIOPrivate::createSymlink(path, symPath);
    if (!symlinkOk) {
        const QString error =
            QString::fromLatin1("Failed to create symlink '%1' pointing to '%2': %3").arg(symPath, path, QString::fromLocal8Bit(strerror(errno)));
        QVERIFY2(symlinkOk, qPrintable(error));
    }
    MyDirLister dirLister2;
    m_items2.clear();
    m_items.clear();
    connect(&dirLister2, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems2);
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    // The initial listing
    m_dirLister.openUrl(QUrl::fromLocalFile(path));
    dirLister2.openUrl(QUrl::fromLocalFile(symPath));
    QTRY_COMPARE(m_items.count(), m_items2.count());
    QTRY_COMPARE(m_items.count(), origItemCount);
    QTRY_VERIFY(dirLister2.isFinished());

    QTest::qWait(100); // We need a 1s timestamp difference on the dir, otherwise FAM won't notice anything.

    qDebug() << "Creating new file";
    const QString fileName = QStringLiteral("toplevelfile_newinlink");
    createSimpleFile(path + fileName);

    if (s_workaroundBrokenInotify) {
        org::kde::KDirNotify::emitFilesAdded(QUrl::fromLocalFile(path));
    }

    // Give time for KDirWatch to notify us
    QTRY_COMPARE(m_items2.count(), origItemCount + 1);
    QTRY_COMPARE(m_items.count(), origItemCount + 1);

    // Now create an item using the symlink-path
    const QString fileName2 = QStringLiteral("toplevelfile_newinlink2");
    {
        createSimpleFile(path + fileName2);

        // Give time for KDirWatch to notify us
        QTRY_COMPARE(m_items2.count(), origItemCount + 2);
        QTRY_COMPARE(m_items.count(), origItemCount + 2);
    }
    QCOMPARE(fileCount(), m_items.count());

    // Test file deletion
    {
        qDebug() << "Deleting" << (path + fileName);
        QTest::qWait(100); // for timestamp difference
        QFile::remove(path + fileName);
        QTRY_COMPARE(dirLister2.spyItemsDeleted.count(), 1);
        QTRY_COMPARE(m_dirLister.spyItemsDeleted.count(), 1);
        const KFileItem item = dirLister2.spyItemsDeleted[0][0].value<KFileItemList>().at(0);
        QCOMPARE(item.url().toLocalFile(), QString(symPath + '/' + fileName));
    }
    // Test file deletion in symlink dir #469254
    {
        qDebug() << "Deleting" << (symPath + "/" + fileName2);
        QTest::qWait(100); // for timestamp difference
        QFile::remove(symPath + "/" + fileName2);
        QTRY_COMPARE(dirLister2.spyItemsDeleted.count(), 2);
        QTRY_COMPARE(m_dirLister.spyItemsDeleted.count(), 2);
        const KFileItem item = dirLister2.spyItemsDeleted[1][0].value<KFileItemList>().at(0);
        QCOMPARE(item.url().toLocalFile(), QString(symPath + '/' + fileName2));
    }

    // TODO: test file update.
    disconnect(&m_dirLister, nullptr, this, nullptr);

    QFile::remove(symPath);
    m_dirLister.openUrl(QUrl::fromLocalFile(tempPath()));
}

// This test assumes testOpenUrl was run before. So m_dirLister is holding the items already.
// Modifies one of the files to have html content
void KDirListerTest::testRefreshItems()
{
    m_refreshedItems.clear();

    const QString path = tempPath();
    const QString fileName = path + "toplevelfile_1";
    KFileItem cachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(fileName));
    QVERIFY(!cachedItem.isNull());
    QCOMPARE(cachedItem.mimetype(), QString("application/octet-stream"));

    connect(&m_dirLister, &KCoreDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems);

    QFile file(fileName);
    QVERIFY(file.open(QIODevice::Append));
    file.write(QByteArray("<html>"));
    file.close();
    QCOMPARE(QFileInfo(fileName).size(), 11LL /*Hello world*/ + 6 /*<html>*/);

    QTRY_VERIFY(!m_refreshedItems.isEmpty());

    QCOMPARE(m_dirLister.spyStarted.count(), 0); // fast path: no directory listing needed
    QVERIFY(m_dirLister.spyCompleted.count() < 2);
    QVERIFY(m_dirLister.spyCompletedQUrl.count() < 2);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 0);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_refreshedItems.count(), 1);
    QPair<KFileItem, KFileItem> entry = m_refreshedItems.first();
    QCOMPARE(entry.first.url().toLocalFile(), fileName);
    QCOMPARE(entry.first.size(), KIO::filesize_t(11));
    QCOMPARE(entry.first.mimetype(), QString("application/octet-stream"));
    QCOMPARE(entry.second.url().toLocalFile(), fileName);
    QCOMPARE(entry.second.size(), KIO::filesize_t(11 /*Hello world*/ + 6 /*<html>*/));
    QCOMPARE(entry.second.mimetype(), QString("text/html"));

    // Let's see what KDirLister has in cache now
    cachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(fileName));
    QCOMPARE(cachedItem.size(), KIO::filesize_t(11 /*Hello world*/ + 6 /*<html>*/));
    m_refreshedItems.clear();
}

// Refresh the root item, plus a hidden file, e.g. changing its icon. #190535
void KDirListerTest::testRefreshRootItem()
{
    // This test assumes testOpenUrl was run before. So m_dirLister is holding the items already.
    m_refreshedItems.clear();
    m_refreshedItems2.clear();

    // The item will be the root item of dirLister2, but also a child item
    // of m_dirLister.
    // In #190535 it would show "." instead of the subdir name, after a refresh...
    const QString path = tempPath() + "subdir";
    MyDirLister dirLister2;
    fillDirLister2(dirLister2, path);

    // Change the subdir by creating a file in it
    waitUntilMTimeChange(path);
    const QString foobar = path + "/.foobar";
    createSimpleFile(foobar);

    connect(&m_dirLister, &KCoreDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems);

    // Arguably, the mtime change of "subdir" should lead to a refreshItem of subdir in the root dir.
    // So the next line shouldn't be necessary, if KDirLister did this correctly. This isn't what this test is about though.
    org::kde::KDirNotify::emitFilesChanged(QList<QUrl>{QUrl::fromLocalFile(path)});
    QTRY_VERIFY(!m_refreshedItems.isEmpty());

    QCOMPARE(m_dirLister.spyStarted.count(), 0);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 0);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_refreshedItems.count(), 1);
    QPair<KFileItem, KFileItem> entry = m_refreshedItems.first();
    QCOMPARE(entry.first.url().toLocalFile(), path);
    QCOMPARE(entry.first.name(), QString("subdir"));
    QCOMPARE(entry.second.url().toLocalFile(), path);
    QCOMPARE(entry.second.name(), QString("subdir"));

    QCOMPARE(m_refreshedItems2.count(), 1);
    entry = m_refreshedItems2.first();
    QCOMPARE(entry.first.url().toLocalFile(), path);
    QCOMPARE(entry.second.url().toLocalFile(), path);
    // item name() doesn't matter here, it's the root item.

    m_refreshedItems.clear();
    m_refreshedItems2.clear();

    waitUntilMTimeChange(path);
    const QString directoryFile = path + "/.directory";
    createSimpleFile(directoryFile);

    org::kde::KDirNotify::emitFilesAdded(QUrl::fromLocalFile(path));
    QTest::qWait(200);
    // The order of these two is not deterministic
    org::kde::KDirNotify::emitFilesChanged(QList<QUrl>{QUrl::fromLocalFile(directoryFile)});
    org::kde::KDirNotify::emitFilesChanged(QList<QUrl>{QUrl::fromLocalFile(path)});
    QTRY_VERIFY(!m_refreshedItems.isEmpty());

    QCOMPARE(m_refreshedItems.count(), 1);
    entry = m_refreshedItems.first();
    QCOMPARE(entry.first.url().toLocalFile(), path);
    QCOMPARE(entry.second.url().toLocalFile(), path);

    m_refreshedItems.clear();
    m_refreshedItems2.clear();

    // Note: this test leaves the .directory file as a side effect.
    // Hidden though, shouldn't matter.
}

void KDirListerTest::testDeleteItem()
{
    testOpenUrl(); // ensure m_items is up-to-date

    const int origItemCount = m_items.count();
    QCOMPARE(fileCount(), origItemCount);
    const QString path = tempPath();

    // qDebug() << "Removing " << path+"toplevelfile_new";
    QFile::remove(path + QString("toplevelfile_new"));
    // the remove() doesn't always trigger kdirwatch in stat mode, if this all happens in the same second
    KDirWatch::self()->setDirty(path);

    // The signal should be emitted once with the deleted file
    QTRY_COMPARE(m_dirLister.spyItemsDeleted.count(), 1);

    // OK now kdirlister told us the file was deleted, let's try a re-listing
    m_items.clear();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
    QVERIFY(!m_dirLister.isFinished());

    QTRY_COMPARE(m_items.count(), origItemCount - 1);
    QVERIFY(m_dirLister.isFinished());

    disconnect(&m_dirLister, nullptr, this, nullptr);
    QCOMPARE(fileCount(), m_items.count());
}

void KDirListerTest::testDeleteItems()
{
    testOpenUrl(); // ensure m_items is up-to-date

    const int origItemCount = m_items.count();
    QCOMPARE(fileCount(), origItemCount);
    const QString path = tempPath();

    qDebug() << "Removing 100 files from " << path;
    for (int i = 0; i <= 100; ++i) {
        QFile::remove(path + QString("toplevelfile_new_%1").arg(i));
    }
    // the remove() doesn't always trigger kdirwatch in stat mode, if this all happens in the same second
    KDirWatch::self()->setDirty(path);

    // The signal could be emitted 1 time with all the deleted files or more times
    QTRY_VERIFY(m_dirLister.spyItemsDeleted.count() > 0);

    // OK now kdirlister told us the file was deleted, let's try a re-listing
    m_items.clear();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
    QTRY_COMPARE(m_items.count(), origItemCount - 100);
    QVERIFY(m_dirLister.isFinished());

    disconnect(&m_dirLister, nullptr, this, nullptr);
    QCOMPARE(fileCount(), m_items.count());
}

void KDirListerTest::testRenameItem()
{
    m_refreshedItems2.clear();
    const QString dirPath = tempPath();
    connect(&m_dirLister, &KCoreDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems2);
    const QString path = dirPath + "toplevelfile_2";
    const QString newPath = dirPath + "toplevelfile_2.renamed.cpp";

    KIO::SimpleJob *job = KIO::rename(QUrl::fromLocalFile(path), QUrl::fromLocalFile(newPath), KIO::HideProgressInfo);
    QVERIFY(job->exec());

    QSignalSpy spyRefreshItems(&m_dirLister, &KCoreDirLister::refreshItems);
    QVERIFY(spyRefreshItems.wait(2000));
    QTRY_COMPARE(m_refreshedItems2.count(), 1);
    QPair<KFileItem, KFileItem> entry = m_refreshedItems2.first();
    QCOMPARE(entry.first.url().toLocalFile(), path);
    QCOMPARE(entry.first.mimetype(), QString("application/octet-stream"));
    QCOMPARE(entry.second.url().toLocalFile(), newPath);
    QCOMPARE(entry.second.mimetype(), QString("text/x-c++src"));
    disconnect(&m_dirLister, nullptr, this, nullptr);

    // Let's see what KDirLister has in cache now
    KFileItem cachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(newPath));
    QVERIFY(!cachedItem.isNull());
    QCOMPARE(cachedItem.url().toLocalFile(), newPath);
    KFileItem oldCachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(path));
    QVERIFY(oldCachedItem.isNull());
    m_refreshedItems2.clear();
}

void KDirListerTest::testRenameAndOverwrite() // has to be run after testRenameItem
{
    // Rename toplevelfile_2.renamed.html to toplevelfile_2, overwriting it.
    const QString dirPath = tempPath();
    const QString path = dirPath + "toplevelfile_2";
    createTestFile(path);

    if (s_workaroundBrokenInotify) {
        org::kde::KDirNotify::emitFilesAdded(QUrl::fromLocalFile(dirPath));
    }

    KFileItem existingItem;
    while (existingItem.isNull()) {
        QTest::qWait(100);
        existingItem = m_dirLister.findByUrl(QUrl::fromLocalFile(path));
    };
    QCOMPARE(existingItem.url().toLocalFile(), path);

    m_refreshedItems.clear();
    connect(&m_dirLister, &KCoreDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems);
    const QString newPath = dirPath + "toplevelfile_2.renamed.cpp";

    KIO::SimpleJob *job = KIO::rename(QUrl::fromLocalFile(newPath), QUrl::fromLocalFile(path), KIO::Overwrite | KIO::HideProgressInfo);
    bool ok = job->exec();
    QVERIFY(ok);

    if (m_refreshedItems.isEmpty()) {
        QTRY_VERIFY(!m_refreshedItems.isEmpty()); // could come from KDirWatch or KDirNotify.
    }

    // Check that itemsDeleted was emitted -- preferably BEFORE refreshItems,
    // but we can't easily check that with QSignalSpy...
    QCOMPARE(m_dirLister.spyItemsDeleted.count(), 1);

    QCOMPARE(m_refreshedItems.count(), 1);
    QPair<KFileItem, KFileItem> entry = m_refreshedItems.first();
    QCOMPARE(entry.first.url().toLocalFile(), newPath);
    QCOMPARE(entry.second.url().toLocalFile(), path);
    disconnect(&m_dirLister, nullptr, this, nullptr);

    // Let's see what KDirLister has in cache now
    KFileItem cachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(path));
    QCOMPARE(cachedItem.url().toLocalFile(), path);
    KFileItem oldCachedItem = m_dirLister.findByUrl(QUrl::fromLocalFile(newPath));
    QVERIFY(oldCachedItem.isNull());
    m_refreshedItems.clear();
}

void KDirListerTest::testConcurrentListing()
{
    const int origItemCount = m_items.count();
    QCOMPARE(fileCount(), origItemCount);
    m_items.clear();
    m_items2.clear();

    MyDirLister dirLister2;

    const QString path = tempPath();

    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    connect(&dirLister2, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems2);

    // Before dirLister2 has time to emit the items, let's make m_dirLister move to another dir.
    // This reproduces the use case "clicking on a folder in dolphin iconview, and dirlister2
    // is the one used by the "folder panel". m_dirLister is going to list the subdir,
    // while dirLister2 wants to list the folder that m_dirLister has just left.
    dirLister2.stop(); // like dolphin does, noop.
    dirLister2.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
    m_dirLister.openUrl(QUrl::fromLocalFile(path + "subdir"), KDirLister::NoFlags);

    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_items.count(), 0);

    QCOMPARE(dirLister2.spyStarted.count(), 1);
    QCOMPARE(dirLister2.spyCompleted.count(), 0);
    QCOMPARE(dirLister2.spyCompletedQUrl.count(), 0);
    QCOMPARE(dirLister2.spyCanceled.count(), 0);
    QCOMPARE(dirLister2.spyCanceledQUrl.count(), 0);
    QCOMPARE(dirLister2.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(dirLister2.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(dirLister2.spyClearDir.count(), 0);

    QCOMPARE(m_items2.count(), 0);
    QVERIFY(!m_dirLister.isFinished());
    QVERIFY(!dirLister2.isFinished());

    // then wait for completed
    qDebug("waiting for completed");

    // QCOMPARE(m_dirLister.spyStarted.count(), 1); // 2 when subdir is already in cache.
    QTRY_COMPARE(m_dirLister.spyCompleted.count(), 1);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_items.count(), 3);

    QTRY_COMPARE(dirLister2.spyStarted.count(), 1);
    QTRY_COMPARE(dirLister2.spyCompleted.count(), 1);
    QCOMPARE(dirLister2.spyCompletedQUrl.count(), 1);
    QCOMPARE(dirLister2.spyCanceled.count(), 0);
    QCOMPARE(dirLister2.spyCanceledQUrl.count(), 0);
    QCOMPARE(dirLister2.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(dirLister2.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(dirLister2.spyClearDir.count(), 0);

    QCOMPARE(m_items2.count(), origItemCount);
    if (!m_dirLister.isFinished()) { // false when an update is running because subdir is already in cache
        // TODO check why this fails QVERIFY(m_dirLister.spyCanceled.wait(1000));
        QTest::qWait(1000);
    }

    disconnect(&m_dirLister, nullptr, this, nullptr);
    disconnect(&dirLister2, nullptr, this, nullptr);
}

void KDirListerTest::testConcurrentHoldingListing()
{
    // #167851.
    // A dirlister holding the items, and a second dirlister does
    // openUrl(reload) (which triggers updateDirectory())
    // and the first lister immediately does openUrl() (which emits cached items).

    testOpenUrl(); // ensure m_dirLister holds the items.
    const int origItemCount = m_items.count();
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    m_items.clear();
    m_items2.clear();
    const QString path = tempPath();
    MyDirLister dirLister2;
    connect(&dirLister2, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems2);

    dirLister2.openUrl(QUrl::fromLocalFile(path), KDirLister::Reload); // will start a list job
    QCOMPARE(dirLister2.spyStarted.count(), 1);
    QCOMPARE(dirLister2.spyCompleted.count(), 0);
    QCOMPARE(m_items.count(), 0);
    QCOMPARE(m_items2.count(), 0);

    qDebug("calling m_dirLister.openUrl");
    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags); // should emit cached items, and then "join" the running listjob
    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_items.count(), 0);
    QCOMPARE(m_items2.count(), 0);

    qDebug("waiting for completed");
    QTRY_COMPARE(dirLister2.spyStarted.count(), 1);
    QTRY_COMPARE(dirLister2.spyCompleted.count(), 1);
    QCOMPARE(dirLister2.spyCompletedQUrl.count(), 1);
    QCOMPARE(dirLister2.spyCanceled.count(), 0);
    QCOMPARE(dirLister2.spyCanceledQUrl.count(), 0);
    QCOMPARE(dirLister2.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(dirLister2.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(dirLister2.spyClearDir.count(), 0);

    QCOMPARE(m_items2.count(), origItemCount);

    QTRY_COMPARE(m_dirLister.spyStarted.count(), 1);
    QTRY_COMPARE(m_dirLister.spyCompleted.count(), 1);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QVERIFY(dirLister2.isFinished());
    QVERIFY(m_dirLister.isFinished());
    disconnect(&m_dirLister, nullptr, this, nullptr);
    QCOMPARE(m_items.count(), origItemCount);
}

void KDirListerTest::testConcurrentListingAndStop()
{
    m_items.clear();
    m_items2.clear();

    MyDirLister dirLister2;

    // Use a new tempdir for this test, so that we don't use the cache at all.
    QTemporaryDir tempDir(homeTmpDir());
    const QString path = tempDir.path() + '/';
    createTestFile(path + "file_1");
    createTestFile(path + "file_2");
    createTestFile(path + "file_3");

    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    connect(&dirLister2, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems2);

    // Before m_dirLister has time to emit the items, let's make dirLister2 call stop().
    // This should not stop the list job for m_dirLister (#267709).
    dirLister2.openUrl(QUrl::fromLocalFile(path), KDirLister::Reload);
    m_dirLister.openUrl(QUrl::fromLocalFile(path) /*, KDirLister::Reload*/);

    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_items.count(), 0);

    QCOMPARE(dirLister2.spyStarted.count(), 1);
    QCOMPARE(dirLister2.spyCompleted.count(), 0);
    QCOMPARE(dirLister2.spyCompletedQUrl.count(), 0);
    QCOMPARE(dirLister2.spyCanceled.count(), 0);
    QCOMPARE(dirLister2.spyCanceledQUrl.count(), 0);
    QCOMPARE(dirLister2.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(dirLister2.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(dirLister2.spyClearDir.count(), 0);

    QCOMPARE(m_items2.count(), 0);
    QVERIFY(!m_dirLister.isFinished());
    QVERIFY(!dirLister2.isFinished());

    dirLister2.stop();

    QCOMPARE(dirLister2.spyStarted.count(), 1);
    QCOMPARE(dirLister2.spyCompleted.count(), 0);
    QCOMPARE(dirLister2.spyCompletedQUrl.count(), 0);
    QCOMPARE(dirLister2.spyCanceled.count(), 1);
    QCOMPARE(dirLister2.spyCanceledQUrl.count(), 1);
    QCOMPARE(dirLister2.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(dirLister2.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(dirLister2.spyClearDir.count(), 0);

    QCOMPARE(m_items2.count(), 0);

    // then wait for completed
    qDebug("waiting for completed");
    QTRY_COMPARE(m_items.count(), 3);
    QTRY_COMPARE(m_items2.count(), 0);
    QTRY_VERIFY(m_dirLister.isFinished());

    // QCOMPARE(m_dirLister.spyStarted.count(), 1); // 2 when in cache
    QCOMPARE(m_dirLister.spyCompleted.count(), 1);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    disconnect(&m_dirLister, nullptr, this, nullptr);
}

void KDirListerTest::testDeleteListerEarly()
{
    // Do the same again, it should behave the same, even with the items in the cache
    testOpenUrl();

    // Start a second lister, it will get a cached items job, but delete it before the job can run
    // qDebug() << "==========================================";
    {
        m_items.clear();
        const QString path = tempPath();
        MyDirLister secondDirLister;
        secondDirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
        QVERIFY(!secondDirLister.isFinished());
    }
    // qDebug() << "==========================================";

    // Check if we didn't keep the deleted dirlister in one of our lists.
    // I guess the best way to do that is to just list the same dir again.
    testOpenUrl();
}

void KDirListerTest::testOpenUrlTwice()
{
    // Calling openUrl(reload)+openUrl(normal) before listing even starts.
    const int origItemCount = m_items.count();
    m_items.clear();
    const QString path = tempPath();
    MyDirLister secondDirLister;
    connect(&secondDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    secondDirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::Reload); // will start
    QCOMPARE(secondDirLister.spyStarted.count(), 1);
    QCOMPARE(secondDirLister.spyCompleted.count(), 0);

    qDebug("calling openUrl again");
    secondDirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags); // will stop + start

    qDebug("waiting for completed");
    QTRY_COMPARE(secondDirLister.spyStarted.count(), 2);
    QTRY_COMPARE(secondDirLister.spyCompleted.count(), 1);
    QCOMPARE(secondDirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(secondDirLister.spyCanceled.count(), 0); // should not be emitted, see next test
    QCOMPARE(secondDirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(secondDirLister.spyClear.count(), 2);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(secondDirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(secondDirLister.spyClearDir.count(), 0);

    if (origItemCount) { // 0 if running this test separately
        QCOMPARE(m_items.count(), origItemCount);
    }
    QVERIFY(secondDirLister.isFinished());
    disconnect(&secondDirLister, nullptr, this, nullptr);
}

void KDirListerTest::testOpenUrlTwiceWithKeep()
{
    // Calling openUrl(reload)+openUrl(keep) on a new dir,
    // before listing even starts (#177387)
    // Well, in 177387 the second openUrl call was made from within slotCanceled
    // called by the first openUrl
    // (slotLoadingFinished -> setCurrentItem -> expandToUrl -> listDir),
    // which messed things up in kdirlister (unexpected reentrancy).
    m_items.clear();
    const QString path = tempPath() + "newsubdir";
    QDir().mkdir(path);
    MyDirLister secondDirLister;
    connect(&secondDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    secondDirLister.openUrl(QUrl::fromLocalFile(path)); // will start a list job
    QCOMPARE(secondDirLister.spyStarted.count(), 1);
    QCOMPARE(secondDirLister.spyCanceled.count(), 0);
    QCOMPARE(secondDirLister.spyCompleted.count(), 0);

    qDebug("calling openUrl again");
    secondDirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::Keep); // stops and restarts the job

    qDebug("waiting for completed");
    QTRY_COMPARE(secondDirLister.spyStarted.count(), 2);
    QTRY_COMPARE(secondDirLister.spyCompleted.count(), 1);
    QCOMPARE(secondDirLister.spyCompletedQUrl.count(), 1);
    QCOMPARE(secondDirLister.spyCanceled.count(), 0); // should not be emitted, it led to recursion
    QCOMPARE(secondDirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(secondDirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(secondDirLister.spyClearQUrl.count(), 1);
#endif
    QCOMPARE(secondDirLister.spyClearDir.count(), 1);

    QCOMPARE(m_items.count(), 0);
    QVERIFY(secondDirLister.isFinished());
    disconnect(&secondDirLister, nullptr, this, nullptr);

    QDir().remove(path);
}

void KDirListerTest::testOpenAndStop()
{
    m_items.clear();
    const QString path = QStringLiteral("/"); // better not use a directory that we already listed!
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
    qDebug() << "Calling stop!";
    m_dirLister.stop(); // we should also test stop(QUrl::fromLocalFile(path))...

    QCOMPARE(m_dirLister.spyStarted.count(), 1); // The call to openUrl itself, emits started
    QCOMPARE(m_dirLister.spyCompleted.count(), 0); // we had time to stop before the job even started
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 1);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 1);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_items.count(), 0); // we had time to stop before the job even started
    QVERIFY(m_dirLister.isFinished());
    disconnect(&m_dirLister, nullptr, this, nullptr);
}

// A bug in the decAutoUpdate/incAutoUpdate logic made KDirLister stop watching a directory for changes,
// and never watch it again when opening it from the cache.
void KDirListerTest::testBug211472()
{
    m_items.clear();

    QTemporaryDir newDir(homeTmpDir());
    const QString path = newDir.path() + "/newsubdir/";
    QDir().mkdir(path);
    MyDirLister dirLister;
    connect(&dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    dirLister.openUrl(QUrl::fromLocalFile(path));
    QVERIFY(dirLister.spyCompleted.wait(1000));
    QVERIFY(dirLister.isFinished());
    QVERIFY(m_items.isEmpty());

    // This block is required to trigger bug 211472.

    // Go 'up' to the parent of 'newsubdir'.
    dirLister.openUrl(QUrl::fromLocalFile(newDir.path()));
    QVERIFY(dirLister.spyCompleted.wait(1000));
    QTRY_VERIFY(dirLister.isFinished());
    QTRY_VERIFY(!m_items.isEmpty());
    m_items.clear();

    // Create a file in 'newsubdir' while we are listing its parent dir.
    createTestFile(path + "newFile-1");
    // At this point, newsubdir is not used, so it's moved to the cache.
    // This happens in checkUpdate, called when receiving a notification for the cached dir,
    // this is why this unittest needs to create a test file in the subdir.

    // wait a second and ensure the list is still empty afterwards
    QTest::qWait(1000);
    QTRY_VERIFY(m_items.isEmpty());

    // Return to 'newsubdir'. It will be emitted from the cache, then an update will happen.
    dirLister.openUrl(QUrl::fromLocalFile(path));
    // Check that completed is emitted twice
    QVERIFY(dirLister.spyCompleted.wait(1000));
    QVERIFY(dirLister.spyCompleted.wait(1000));
    QTRY_VERIFY(dirLister.isFinished());
    QTRY_COMPARE(m_items.count(), 1);
    m_items.clear();

    // Now try to create a second file in 'newsubdir' and verify that the
    // dir lister notices it.
    QTest::qWait(1000); // We need a 1s timestamp difference on the dir, otherwise FAM won't notice anything.

    createTestFile(path + "newFile-2");
    QTRY_COMPARE(m_items.count(), 1);

    newDir.remove();
    QSignalSpy spyClear(&dirLister, qOverload<>(&KCoreDirLister::clear));
    QVERIFY(spyClear.wait(1000));
}

void KDirListerTest::testRenameCurrentDir() // #294445
{
    m_items.clear();

    const QString path = tempPath() + "newsubdir-1";
    QVERIFY(QDir().mkdir(path));
    MyDirLister secondDirLister;
    connect(&secondDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    secondDirLister.openUrl(QUrl::fromLocalFile(path));
    QSignalSpy spyCompleted(&secondDirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));
    QVERIFY(secondDirLister.isFinished());
    QVERIFY(m_items.empty());
    QCOMPARE(secondDirLister.rootItem().url().toLocalFile(), path);

    const QString newPath = tempPath() + "newsubdir-2";
    QVERIFY(QDir().rename(path, newPath));
    org::kde::KDirNotify::emitFileRenamed(QUrl::fromLocalFile(path), QUrl::fromLocalFile(newPath));
    QSignalSpy spyRedirection(&secondDirLister, qOverload<const QUrl &, const QUrl &>(&KCoreDirLister::redirection));
    QVERIFY(spyRedirection.wait(1000));

    // Check that the URL of the root item got updated
    QCOMPARE(secondDirLister.rootItem().url().toLocalFile(), newPath);

    disconnect(&secondDirLister, nullptr, this, nullptr);
    QDir().rmdir(newPath);
}

void KDirListerTest::slotOpenUrlOnRename(const QUrl &newUrl)
{
    QVERIFY(m_dirLister.openUrl(newUrl));
}

// This tests for a crash if you connect redirects to openUrl, due
// to internal data being inconsistently exposed.
// Matches usage in gwenview.
void KDirListerTest::testRenameCurrentDirOpenUrl()
{
    m_items.clear();
    const QString path = tempPath() + "newsubdir-1/";
    QVERIFY(QDir().mkdir(path));
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);

    m_dirLister.openUrl(QUrl::fromLocalFile(path));
    QSignalSpy spyCompleted(&m_dirLister, qOverload<>(&KCoreDirLister::completed));
    // Wait for the signal completed to be emitted
    QVERIFY(spyCompleted.wait(1000));
    QVERIFY(m_dirLister.isFinished());

    const QString newPath = tempPath() + "newsubdir-2";
    QVERIFY(QDir().rename(path, newPath));

    org::kde::KDirNotify::emitFileRenamed(QUrl::fromLocalFile(path), QUrl::fromLocalFile(newPath));

    // Connect the redirection to openURL, so that on a rename the new location is opened.
    // This matches usage in gwenview, and crashes
#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 80)
    connect(&m_dirLister, qOverload<const QUrl &>(&KCoreDirLister::redirection), this, &KDirListerTest::slotOpenUrlOnRename);
#else
    connect(&m_dirLister, qOverload<const QUrl &, const QUrl &>(&KCoreDirLister::redirection), this, [this](const QUrl &, const QUrl &newUrl) {
        slotOpenUrlOnRename(newUrl);
    });
#endif

    QTRY_VERIFY(m_dirLister.isFinished());
    disconnect(&m_dirLister, nullptr, this, nullptr);
    QDir().rmdir(newPath);
}

void KDirListerTest::testRedirection()
{
    m_items.clear();
    const QUrl url(QStringLiteral("file://somemachine/"));

    if (!KProtocolInfo::isKnownProtocol(QStringLiteral("smb"))) {
        QSKIP("smb not installed");
    }

    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    // The call to openUrl itself, emits started
    m_dirLister.openUrl(url, KDirLister::NoFlags);

    QCOMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0);
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QCOMPARE(m_dirLister.spyRedirection.count(), 0);
    QCOMPARE(m_items.count(), 0);
    QVERIFY(!m_dirLister.isFinished());

    // then wait for the redirection signal
    qDebug("waiting for redirection");
    QTRY_COMPARE(m_dirLister.spyStarted.count(), 1);
    QCOMPARE(m_dirLister.spyCompleted.count(), 0); // we stopped before the listing.
    QCOMPARE(m_dirLister.spyCompletedQUrl.count(), 0);
    QCOMPARE(m_dirLister.spyCanceled.count(), 0);
    QCOMPARE(m_dirLister.spyCanceledQUrl.count(), 0);
    QTRY_COMPARE(m_dirLister.spyClear.count(), 2); // redirection cleared a second time (just in case...)

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QTRY_COMPARE(m_dirLister.spyRedirection.count(), 1);
    QVERIFY(m_items.isEmpty());
    QVERIFY(!m_dirLister.isFinished());

    m_dirLister.stop(url);
    QVERIFY(!m_dirLister.isFinished());
    disconnect(&m_dirLister, nullptr, this, nullptr);
}

void KDirListerTest::testListEmptyDirFromCache() // #278431
{
    m_items.clear();

    QTemporaryDir newDir(homeTmpDir());
    const QUrl url = QUrl::fromLocalFile(newDir.path());

    // List and watch an empty dir
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    m_dirLister.openUrl(url);
    QSignalSpy spyCompleted(&m_dirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));
    QVERIFY(m_dirLister.isFinished());
    QVERIFY(m_items.isEmpty());

    // List it with two more dirlisters (one will create a cached items job, the second should also benefit from it)
    MyDirLister secondDirLister;
    connect(&secondDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    secondDirLister.openUrl(url);
    MyDirLister thirdDirLister;
    connect(&thirdDirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    thirdDirLister.openUrl(url);

    // The point of this test is that (with DEBUG_CACHE enabled) it used to assert here
    // with "HUH? Lister KDirLister(0x7ffd1f044260) is supposed to be listing, but has no job!"
    // due to the if (!itemU->lstItems.isEmpty()) check which is now removed.

    QVERIFY(!secondDirLister.isFinished()); // we didn't go to the event loop yet
    QSignalSpy spySecondCompleted(&secondDirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spySecondCompleted.wait(1000));
    if (!thirdDirLister.isFinished()) {
        QSignalSpy spyThirdCompleted(&thirdDirLister, qOverload<>(&KCoreDirLister::completed));
        QVERIFY(spyThirdCompleted.wait(1000));
    }
}

void KDirListerTest::testWatchingAfterCopyJob() // #331582
{
    m_items.clear();

    QTemporaryDir newDir(homeTmpDir());
    const QString path = newDir.path() + '/';

    // List and watch an empty dir
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    m_dirLister.openUrl(QUrl::fromLocalFile(path));
    QSignalSpy spyCompleted(&m_dirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));
    QVERIFY(m_dirLister.isFinished());
    QVERIFY(m_items.isEmpty());

    // Create three subfolders.
    QVERIFY(QDir().mkdir(path + "New Folder"));
    QVERIFY(QDir().mkdir(path + "New Folder 1"));
    QVERIFY(QDir().mkdir(path + "New Folder 2"));

    QVERIFY(spyCompleted.wait(1000));
    QTRY_VERIFY(m_dirLister.isFinished());
    QTRY_COMPARE(m_items.count(), 3);

    // Create a new file and verify that the dir lister notices it.
    m_items.clear();
    createTestFile(path + QLatin1Char('a'));
    QVERIFY(spyCompleted.wait(1000));
    QTRY_VERIFY(m_dirLister.isFinished());
    QTRY_COMPARE(m_items.count(), 1);

    // Rename one of the subfolders.
    const QString oldPath = path + "New Folder 1";
    const QString newPath = path + "New Folder 1a";

    // NOTE: The following two lines are required to trigger the bug!
    KIO::Job *job = KIO::moveAs(QUrl::fromLocalFile(oldPath), QUrl::fromLocalFile(newPath), KIO::HideProgressInfo);
    job->exec();

    // Now try to create a second new file and verify that the
    // dir lister notices it.
    m_items.clear();
    createTestFile(path + QLatin1Char('b'));

    // This should end up in "KCoreDirListerCache::slotFileDirty"
    QTRY_COMPARE(m_items.count(), 1);

    newDir.remove();
    QSignalSpy clearSpy(&m_dirLister, qOverload<>(&KCoreDirLister::clear));
    QVERIFY(clearSpy.wait(1000));
}

void KDirListerTest::testRemoveWatchedDirectory()
{
    m_items.clear();

    QTemporaryDir newDir(homeTmpDir());
    const QString path = newDir.path() + '/';

    // List and watch an empty dir
    connect(&m_dirLister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    m_dirLister.openUrl(QUrl::fromLocalFile(path));
    QSignalSpy spyCompleted(&m_dirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));
    QTRY_VERIFY(m_dirLister.isFinished());
    QTRY_VERIFY(m_items.isEmpty());

    // Create a subfolder.
    const QString subDirPath = path + "abc";
    QVERIFY(QDir().mkdir(subDirPath));

    QVERIFY(spyCompleted.wait(1000));
    QTRY_VERIFY(m_dirLister.isFinished());
    QTRY_COMPARE(m_items.count(), 1);
    const KFileItem item = m_items.at(0);

    // Watch the subfolder for changes, independently.
    // This is what triggers the bug.
    // (Technically, this could become a KDirWatch unittest, but if one day we use QFSW, good to have the tests here)
    KDirWatch watcher;
    watcher.addDir(subDirPath);

    // Remove the subfolder.
    m_items.clear();
    QVERIFY(QDir().rmdir(path + "abc"));

    // This should trigger an update.
    QVERIFY(spyCompleted.wait(1000));
    QVERIFY(m_dirLister.isFinished());
    QCOMPARE(m_items.count(), 0);
    QCOMPARE(m_dirLister.spyItemsDeleted.count(), 1);
    const KFileItem deletedItem = m_dirLister.spyItemsDeleted.at(0).at(0).value<KFileItemList>().at(0);
    QCOMPARE(item, deletedItem);
}

void KDirListerTest::testDirPermissionChange()
{
    QTemporaryDir tempDir(homeTmpDir());

    const QString path = tempDir.path() + '/';
    const QString subdir = path + QLatin1String("subdir");
    QVERIFY(QDir().mkdir(subdir));

    MyDirLister mylister;
    mylister.openUrl(QUrl::fromLocalFile(tempDir.path()));
    QSignalSpy spyCompleted(&mylister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));

    KFileItemList list = mylister.items();
    QVERIFY(mylister.isFinished());
    QCOMPARE(list.count(), 1);
    QCOMPARE(mylister.rootItem().url().toLocalFile(), tempDir.path());

    const mode_t permissions = (S_IRUSR | S_IWUSR | S_IXUSR);
    KIO::SimpleJob *job = KIO::chmod(list.first().url(), permissions);
    QVERIFY(job->exec());

    QSignalSpy spyRefreshItems(&mylister, &KCoreDirLister::refreshItems);
    QVERIFY(spyRefreshItems.wait(2000));

    list = mylister.items();
    QCOMPARE(list.first().permissions(), permissions);
    QVERIFY(QDir().rmdir(subdir));
}

void KDirListerTest::slotNewItems(const KFileItemList &lst)
{
    m_items += lst;
}

void KDirListerTest::slotNewItems2(const KFileItemList &lst)
{
    m_items2 += lst;
}

void KDirListerTest::slotRefreshItems(const QList<QPair<KFileItem, KFileItem>> &lst)
{
    m_refreshedItems += lst;
    Q_EMIT refreshItemsReceived();
}

void KDirListerTest::slotRefreshItems2(const QList<QPair<KFileItem, KFileItem>> &lst)
{
    m_refreshedItems2 += lst;
}

void KDirListerTest::testCopyAfterListingAndMove() // #353195
{
    const QString dirA = tempPath() + "a";
    QVERIFY(QDir().mkdir(dirA));
    const QString dirB = tempPath() + "b";
    QVERIFY(QDir().mkdir(dirB));

    // ensure m_dirLister holds the items.
    m_dirLister.openUrl(QUrl::fromLocalFile(tempPath()), KDirLister::NoFlags);
    QSignalSpy spyCompleted(&m_dirLister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait());

    // Move b into a
    KIO::Job *moveJob = KIO::move(QUrl::fromLocalFile(dirB), QUrl::fromLocalFile(dirA));
    moveJob->setUiDelegate(nullptr);
    QVERIFY(moveJob->exec());
    QVERIFY(QFileInfo(tempPath() + "a/b").isDir());

    // Give some time to processPendingUpdates
    QTest::qWait(1000);

    // Copy folder a elsewhere
    const QString dest = tempPath() + "subdir";
    KIO::Job *copyJob = KIO::copy(QUrl::fromLocalFile(dirA), QUrl::fromLocalFile(dest));
    copyJob->setUiDelegate(nullptr);
    QVERIFY(copyJob->exec());
    QVERIFY(QFileInfo(tempPath() + "subdir/a/b").isDir());
}

void KDirListerTest::testRenameDirectory() // #401552
{
    // Create the directory structure to reproduce the bug in a reliable way
    const QString dirW = tempPath() + "w";
    QVERIFY(QDir().mkdir(dirW));
    const QString dirW1 = tempPath() + "w/Files";
    QVERIFY(QDir().mkdir(dirW1));
    const QString dirW2 = tempPath() + "w/Files/Files";
    QVERIFY(QDir().mkdir(dirW2));
    // Place some empty files in each directory
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW + QString("t_%1").arg(i));
    }
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW + QString("z_%1").arg(i));
    }
    // Place some empty files with prefix Files in w. Note that / is missing.
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW1 + QString("t_%1").arg(i));
    }
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW1 + QString("z_%1").arg(i));
    }
    // Place some empty files with prefix Files in w/Files. Note that / is missing.
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW2 + QString("t_%1").arg(i));
    }
    for (int i = 0; i < 50; i++) {
        createSimpleFile(dirW2 + QString("z_%1").arg(i));
    }
    // Listen to the w directory
    m_dirLister.openUrl(QUrl::fromLocalFile(dirW), KDirLister::NoFlags);

    // Try to reproduce the bug #401552 renaming the w directory several times if needed
    const QStringList dirs = {dirW + "___", dirW + QLatin1Char('_'), dirW + "______", dirW + "_c", dirW + "___", dirW + "_________"};

    QString currDir = dirW;
    KIO::SimpleJob *job = nullptr;
    // Connect the redirection to openURL, so that on a rename the new location is opened.
#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 80)
    connect(&m_dirLister, qOverload<const QUrl &>(&KCoreDirLister::redirection), this, &KDirListerTest::slotOpenUrlOnRename);
#else
    connect(&m_dirLister, qOverload<const QUrl &, const QUrl &>(&KCoreDirLister::redirection), this, [this](const QUrl &, const QUrl &newUrl) {
        slotOpenUrlOnRename(newUrl);
    });
#endif

    for (int i = 0; i < dirs.size(); i++) {
        // Wait for the listener to get all files
        QTRY_VERIFY(m_dirLister.isFinished());
        // Do the rename
        QString newDir = dirs.at(i);
        job = KIO::rename(QUrl::fromLocalFile(currDir), QUrl::fromLocalFile(newDir), KIO::HideProgressInfo);
        QVERIFY2(job->exec(), qPrintable(job->errorString()));
        QTest::qWait(500); // Without the delay the crash doesn't happen
        currDir = newDir;
    }
    disconnect(&m_dirLister, nullptr, this, nullptr);
}

void KDirListerTest::testRequestMimeType()
{
    // Use a new tempdir and lister instance for this test, so that we don't use any cache at all.
    QTemporaryDir tempDir(homeTmpDir());
    QString path = tempDir.path() + QLatin1Char('/');

    createTestFile(path + "/file_1");
    createTestFile(path + "/file_2.txt");
    createTestFile(path + "/file_3.cpp");
    createTestFile(path + "/file_3.md");

    MyDirLister lister;
    // Explicitly set requestMimeTypeWhileListing to false so we know what state
    // it is in.
    lister.setRequestMimeTypeWhileListing(false);
    lister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);

    QTRY_VERIFY(lister.isFinished());

    auto items = lister.items();
    for (auto item : std::as_const(items)) {
        QVERIFY(!item.isMimeTypeKnown());
    }

    // Verify that the mime types are what we expect them to be
    QCOMPARE(items[0].mimetype(), QStringLiteral("application/octet-stream"));
    QCOMPARE(items[1].mimetype(), QStringLiteral("text/plain"));
    QCOMPARE(items[2].mimetype(), QStringLiteral("text/x-c++src"));
    QCOMPARE(items[3].mimetype(), QStringLiteral("text/markdown"));

    lister.setRequestMimeTypeWhileListing(true);
    lister.openUrl(QUrl::fromLocalFile(path), KDirLister::Reload);

    QTRY_VERIFY(lister.isFinished());

    // If requestMimeTypeWhileListing is on, we should know the mime type of
    // items when they have been listed.
    items = lister.items();
    for (auto item : std::as_const(items)) {
        QVERIFY(item.isMimeTypeKnown());
    }

    // Verify that the mime types are what we expect them to be
    QCOMPARE(items[0].mimetype(), QStringLiteral("application/octet-stream"));
    QCOMPARE(items[1].mimetype(), QStringLiteral("text/plain"));
    QCOMPARE(items[2].mimetype(), QStringLiteral("text/x-c++src"));
    QCOMPARE(items[3].mimetype(), QStringLiteral("text/markdown"));
}

void KDirListerTest::testMimeFilter_data()
{
    QTest::addColumn<QStringList>("files");
    QTest::addColumn<QStringList>("mimeTypes");
    QTest::addColumn<QStringList>("filteredFiles");

    const QStringList files = {"bla.txt", "main.cpp", "main.c", "image.jpeg"};

    QTest::newRow("single_file_exact_mimetype") << files << QStringList{"text/x-c++src"} << QStringList{"main.cpp"};
    QTest::newRow("inherited_mimetype") << files << QStringList{"text/plain"} << QStringList{"bla.txt", "main.cpp", "main.c"};
    QTest::newRow("no_match") << files << QStringList{"audio/flac"} << QStringList{};
}

void KDirListerTest::testMimeFilter()
{
    // Use a new tempdir and lister instance for this test, so that we don't use any cache at all.
    QTemporaryDir tempDir(homeTmpDir());
    QString path = tempDir.path() + '/';

    QFETCH(QStringList, files);
    QFETCH(QStringList, mimeTypes);
    QFETCH(QStringList, filteredFiles);

    for (const QString &fileName : files) {
        createTestFile(path + fileName);
    }

    MyDirLister lister;
    lister.setMimeFilter(mimeTypes);
    lister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);

    QSignalSpy spyCompleted(&lister, qOverload<>(&KCoreDirLister::completed));
    QVERIFY(spyCompleted.wait(1000));

    QCOMPARE(lister.items().size(), filteredFiles.size());

    const auto items = lister.items();
    for (const auto &item : items) {
        QVERIFY(filteredFiles.indexOf(item.name()) != -1);
    }
}

void KDirListerTest::testDeleteCurrentDir()
{
    // ensure m_dirLister holds the items.
    m_dirLister.openUrl(QUrl::fromLocalFile(tempPath()), KDirLister::NoFlags);
    m_dirLister.clearSpies();
    KIO::DeleteJob *job = KIO::del(QUrl::fromLocalFile(tempPath()), KIO::HideProgressInfo);
    bool ok = job->exec();
    QVERIFY(ok);
    QTRY_COMPARE(m_dirLister.spyClear.count(), 1);

#if KIOCORE_BUILD_DEPRECATED_SINCE(5, 79)
    QCOMPARE(m_dirLister.spyClearQUrl.count(), 0);
#endif
    QCOMPARE(m_dirLister.spyClearDir.count(), 0);

    QList<QUrl> deletedUrls;
    for (int i = 0; i < m_dirLister.spyItemsDeleted.count(); ++i) {
        deletedUrls += m_dirLister.spyItemsDeleted[i][0].value<KFileItemList>().urlList();
    }
    // qDebug() << deletedUrls;
    QUrl currentDirUrl = QUrl::fromLocalFile(tempPath()).adjusted(QUrl::StripTrailingSlash);
    // Sometimes I get ("current/subdir", "current") here, but that seems ok.
    QVERIFY(deletedUrls.contains(currentDirUrl));
}

void KDirListerTest::testForgetDir()
{
    QTemporaryDir tempDir(homeTmpDir());
    QString path = tempDir.path();
    createTestFile(path + "/file_1");

    m_dirLister.openUrl(QUrl::fromLocalFile(path), KDirLister::Keep);
    QVERIFY(m_dirLister.spyCompleted.wait());

    m_dirLister.forgetDirs(QUrl::fromLocalFile(path));

    QSignalSpy addedSpy(&m_dirLister, &MyDirLister::itemsAdded);
    createTestFile(path + "/file_2");
    QVERIFY(!addedSpy.wait(1000)); // to allow for KDirWatch's internal 500ms timer
}

int KDirListerTest::fileCount() const
{
    return QDir(tempPath()).entryList(QDir::AllEntries | QDir::NoDotAndDotDot).count();
}

void KDirListerTest::createSimpleFile(const QString &fileName)
{
    QFile file(fileName);
    QVERIFY(file.open(QIODevice::WriteOnly));
    file.write(QByteArray("foo"));
    file.close();
}

void KDirListerTest::fillDirLister2(MyDirLister &lister, const QString &path)
{
    m_items2.clear();
    connect(&lister, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems2);
    connect(&m_dirLister, &KCoreDirLister::refreshItems, this, &KDirListerTest::slotRefreshItems2);
    lister.openUrl(QUrl::fromLocalFile(path), KDirLister::NoFlags);
    QTRY_VERIFY(lister.isFinished());
}

void KDirListerTest::waitUntilMTimeChange(const QString &path)
{
    // Wait until the current second is more than the file's mtime
    // otherwise this change will go unnoticed

    QFileInfo fi(path);
    QVERIFY(fi.exists());
    const QDateTime mtime = fi.lastModified();
    waitUntilAfter(mtime);
}

void KDirListerTest::waitUntilAfter(const QDateTime &ctime)
{
    int totalWait = 0;
    QDateTime now;
    Q_FOREVER {
        now = QDateTime::currentDateTime();
        if (now.toSecsSinceEpoch() == ctime.toSecsSinceEpoch()) { // truncate milliseconds
            totalWait += 50;
            QTest::qWait(50);
        } else {
            QVERIFY(now > ctime); // can't go back in time ;)
            QTest::qWait(50); // be safe
            break;
        }
    }
    // if (totalWait > 0)
    qDebug() << "Waited" << totalWait << "ms so that now" << now.toString(Qt::ISODate) << "is >" << ctime.toString(Qt::ISODate);
}

// A bug in the decAutoUpdate/incAutoUpdate logic made KDirLister stop watching a directory for changes,
// and stop watching a directory because a separate lister left a directory open in another lister
void KDirListerTest::testBug386763()
{
    QTemporaryDir newDir(homeTmpDir());
    const QString path = newDir.path() + "/newsubdir/";
    const QString otherpath = newDir.path() + "/othersubdir/";

    QDir().mkdir(path);
    MyDirLister dirLister;
    dirLister.openUrl(QUrl::fromLocalFile(path));

    // second lister opening same dir
    MyDirLister dirLister2;
    dirLister2.openUrl(QUrl::fromLocalFile(path));
    QCOMPARE(dirLister2.spyCompleted.count(), 0);

    connect(&dirLister2, &KCoreDirLister::newItems, this, &KDirListerTest::slotNewItems);
    QVERIFY(dirLister.spyCompleted.wait(500));
    QVERIFY(dirLister.isFinished());
    QVERIFY(m_items.isEmpty());

    // first lister opening another dir
    dirLister.openUrl(QUrl::fromLocalFile(otherpath));

    // Create a file in 'newsubdir' while still opened in dirLister2
    // bug was that the watch on ’newsubdir’ when dirLister left this dir
    // eventhough dirLister2 is still listing it
    QCOMPARE(dirLister2.spyCompleted.count(), 1);
    createTestFile(path + "newFile-1");

    QTRY_COMPARE(m_items.count(), 1);
    QVERIFY(KDirWatch::self()->contains(path));

    dirLister2.openUrl(QUrl::fromLocalFile(otherpath));
    // checks we still watch the old path when second lister leaves it as it should be now in cache
    QVERIFY(KDirWatch::self()->contains(path));

    newDir.remove();
}

void KDirListerTest::testCacheEviction()
{
    QTemporaryDir newDir(homeTmpDir());

    MyDirLister dirLister;
    dirLister.openUrl(QUrl::fromLocalFile(newDir.path()));
    QVERIFY(dirLister.spyCompleted.wait(500));
    QVERIFY(dirLister.isFinished());
    QVERIFY(KDirWatch::self()->contains(newDir.path()));

    for (int i = 0; i < 12; i++) {
        const QString newDirPath = newDir.path() + QString("dir_%1").arg(i);
        QVERIFY(QDir().mkdir(newDirPath));

        dirLister.openUrl(QUrl::fromLocalFile(newDirPath));
        QVERIFY(dirLister.spyCompleted.wait(500));
        QVERIFY(dirLister.isFinished());
        QVERIFY(KDirWatch::self()->contains(newDirPath));
    }

    // watches were removed as the dirItem were evicted from cache
    QVERIFY(!KDirWatch::self()->contains(newDir.path()));
    QVERIFY(!KDirWatch::self()->contains(newDir.path() + QString("dir_0")));
    QVERIFY(KDirWatch::self()->contains(newDir.path() + QString("dir_1")));
}

#include "moc_kdirlistertest.cpp"