summaryrefslogtreecommitdiffstats
path: root/tests/auto/qjsondbrequest/testqjsondbrequest.cpp
blob: cdd20f373cd80c7323cd3c943b1641f0072fb6f6 (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
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
/****************************************************************************
 **
 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
 ** Contact: http://www.qt-project.org/
 **
 ** This file is part of the QtAddOn.JsonDb module of the Qt Toolkit.
 **
 ** $QT_BEGIN_LICENSE:LGPL$
 ** GNU Lesser General Public License Usage
 ** This file may be used under the terms of the GNU Lesser General Public
 ** License version 2.1 as published by the Free Software Foundation and
 ** appearing in the file LICENSE.LGPL included in the packaging of this
 ** file. Please review the following information to ensure the GNU Lesser
 ** General Public License version 2.1 requirements will be met:
 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
 **
 ** In addition, as a special exception, Nokia gives you certain additional
 ** rights. These rights are described in the Nokia Qt LGPL Exception
 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
 **
 ** GNU General Public License Usage
 ** Alternatively, this file may be used under the terms of the GNU General
 ** Public License version 3.0 as published by the Free Software Foundation
 ** and appearing in the file LICENSE.GPL included in the packaging of this
 ** file. Please review the following information to ensure the GNU General
 ** Public License version 3.0 requirements will be met:
 ** http://www.gnu.org/copyleft/gpl.html.
 **
 ** Other Usage
 ** Alternatively, this file may be used in accordance with the terms and
 ** conditions contained in a signed written agreement between you and Nokia.
 **
 **
 **
 **
 **
 **
 ** $QT_END_LICENSE$
 **
 ****************************************************************************/

#include "qjsondbconnection.h"
#include "qjsondbobject.h"
#include "qjsondbreadrequest.h"
#include "qjsondbwriterequest.h"
#include "private/qjsondbstandardpaths_p.h"
#include "private/qjsondbflushrequest_p.h"
#include "testhelper.h"

#include <QDebug>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QProcess>
#include <QTest>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QTimer>
#include <QTemporaryDir>
#include <QThread>
#include <QSignalSpy>

#include <pwd.h>
#include <signal.h>

#ifdef Q_OS_UNIX
#include <unistd.h>
#endif

QT_USE_NAMESPACE_JSONDB

inline static const QString typeStr() { return QStringLiteral("_type"); }
inline static const QString uuidStr() { return QStringLiteral("_uuid"); }
inline static const QString versionStr() { return QStringLiteral("_version"); }

/*!
    The TestQJsonDbRequest class tests the different QJsonDbRequest objects.
    Currently QJsonDbReadRequest, QJsonDbCreateRequest, QJsonDbUpdateRequest,
    QJsonDbRemoveRequest.
*/
class TestQJsonDbRequest: public TestHelper
{
    Q_OBJECT

public slots:
    void writeAndRemove();
    void severalWrites();

private slots:
    void initTestCase();
    void cleanupTestCase();
    void init();
    void cleanup();

    void modifyPartitions();
    void closeIndexes();
    void removablePartition();
    void readRequest_data();
    void readRequest();
    void writeRequest_data();
    void writeRequest();
    void createRequest_data();
    void createRequest();
    void updateRequest_data();
    void updateRequest();
    void privatePartition();
    void privatePartition2();
    void privatePartitions();
    void invalidPrivatePartition();
    void removeRequest();
    void forced();
    void readObjectRequest();
    void bindings();
    void replaceFromNull();
    void multiplerequests();
    void defaultConnection();
    void privatePartitionFlushRequest();
    void multipleThreads_data();
    void multipleThreads();
    void defaultPartition();

private:
    bool writeTestObject(QObject* parent, const QString &type, int value, const QString &partition = QString());
};

void TestQJsonDbRequest::initTestCase()
{
    QJsonDbStandardPaths::setAutotestMode(true);
    removeDbFiles();

    QStringList arg_list = QStringList() << "-validate-schemas";
    launchJsonDbDaemon(arg_list, __FILE__);
}

void TestQJsonDbRequest::cleanupTestCase()
{
    removeDbFiles();

    QFile partitionsFile(QFileInfo(QFINDTESTDATA("partitions.json")).absoluteDir().absoluteFilePath(QLatin1String("partitions-test.json")));
    partitionsFile.remove();

    stopDaemon();
}

void TestQJsonDbRequest::init()
{
    clearHelperData();
    connectToServer();
}

void TestQJsonDbRequest::cleanup()
{
    disconnectFromServer();
}

void TestQJsonDbRequest::modifyPartitions()
{
    // create a notification on Partitions
    QJsonDbWatcher watcher;
    watcher.setPartition(QLatin1String("Ephemeral"));
    watcher.setQuery("[?_type=\"Partition\"]");
    mConnection->addWatcher(&watcher);

    // ensure that there's only one partition defined and that it's the default
    QLatin1String defaultPartition("com.qt-project.shared");

    QJsonDbReadRequest partitionQuery;
    partitionQuery.setPartition(QLatin1String("Ephemeral"));
    partitionQuery.setQuery(QLatin1String("[?_type=%type]"));
    partitionQuery.bindValue(QLatin1String("type"), QLatin1String("Partition"));

    mConnection->send(&partitionQuery);
    QVERIFY(waitForResponse(&partitionQuery));

    QList<QJsonObject> results = partitionQuery.takeResults();
    QCOMPARE(results.count(), 1);
    QCOMPARE(results[0].value(QLatin1String("name")).toString(), defaultPartition);
    QVERIFY(results[0].value(QLatin1String("default")).toBool());

    // write a new partitions file
    QJsonObject def1;
    def1.insert(QLatin1String("name"), QLatin1String("com.qt-project.test1"));
    def1.insert(QLatin1String("path"), QLatin1String("."));
    QJsonObject def2;
    def2.insert(QLatin1String("name"), QLatin1String("com.qt-project.test2"));
    def2.insert(QLatin1String("path"), QLatin1String("."));
    QJsonArray defs;
    defs.append(def1);
    defs.append(def2);

    // ensure that the new file is written to the same directory as the main partitions.json
    QFile partitionsFile(QFileInfo(QFINDTESTDATA("partitions.json")).absoluteDir().absoluteFilePath(QLatin1String("partitions-test.json")));
    partitionsFile.open(QFile::WriteOnly);
    partitionsFile.write(QJsonDocument(defs).toJson());
    partitionsFile.close();

    // send the daemon a SIGHUP to get it to reload the partitions
    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 2));

    // query for the new partitions
    mConnection->send(&partitionQuery);
    QVERIFY(waitForResponse(&partitionQuery));

    results = partitionQuery.takeResults();
    QCOMPARE(results.count(), 3);

    // operate on the new partition to make sure it works
    QJsonDbWriteRequest writeRequest;
    QUuid testUuid = QJsonDbObject::createUuidFromString(QLatin1String("testobject1"));
    QJsonDbObject toWrite;
    toWrite.setUuid(testUuid);
    toWrite.insert(QLatin1String("_type"), QLatin1String("TestObject"));
    writeRequest.setObjects(QList<QJsonObject>() << toWrite);
    mConnection->send(&writeRequest);
    QVERIFY(waitForResponse(&writeRequest));
    QVERIFY(!mRequestErrors.contains(&writeRequest));

    QJsonDbReadObjectRequest readRequest(testUuid);
    mConnection->send(&readRequest);
    QVERIFY(waitForResponse(&readRequest));
    QVERIFY(!mRequestErrors.contains(&readRequest));
    results = readRequest.takeResults();
    QCOMPARE(results.count(), 1);
    QCOMPARE(results[0].value(QLatin1String("_type")).toString(), QLatin1String("TestObject"));

    // remove the new partitions file
    partitionsFile.remove();

    // send the daemon a SIGHUP to get it to unload the partitions
    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 2));

    // verify that we're back to just the origin partition
    mConnection->send(&partitionQuery);
    QVERIFY(waitForResponse(&partitionQuery));

    results = partitionQuery.takeResults();
    QCOMPARE(results.count(), 1);
    QCOMPARE(results[0].value(QLatin1String("name")).toString(), defaultPartition);
    QVERIFY(results[0].value(QLatin1String("default")).toBool());

    // query one of the test partitions to ensure we get an InvalidPartition error
    QJsonDbReadRequest failingRequest;
    failingRequest.setPartition(QLatin1String("com.qt-project.test1"));
    failingRequest.setQuery(QLatin1String("[*]"));
    mConnection->send(&failingRequest);
    QVERIFY(waitForResponse(&failingRequest));

    QVERIFY(mRequestErrors.contains(&failingRequest));
    QCOMPARE(mRequestErrors[&failingRequest], QJsonDbRequest::InvalidPartition);

    mConnection->removeWatcher(&watcher);
    waitForStatus(&watcher, QJsonDbWatcher::Inactive);
}

void TestQJsonDbRequest::closeIndexes()
{
    {
        QList<QJsonObject> objects;
        QJsonDbObject object;
        object.setUuid(QJsonDbObject::createUuid());
        object.insert(QLatin1String("_type"), QLatin1String("duck"));
        object.insert(QLatin1String("foobar"), QLatin1String("bazinga"));
        objects.append(object);
        QJsonDbWriteRequest writeRequest;
        writeRequest.setObjects(objects);
        mConnection->send(&writeRequest);
        waitForResponse(&writeRequest);
        QVERIFY(!mRequestErrors.contains(&writeRequest));
    }

    {
        // create 3 indexes
        QList<QJsonObject> indexes;
        for (int i = 0; i < 3; ++i) {
            QJsonDbObject index;
            index.setUuid(QJsonDbObject::createUuid());
            index.insert(QLatin1String("_type"), QLatin1String("Index"));
            index.insert(QLatin1String("name"), QString(QLatin1String("closeIndexesTest%1")).arg(i));
            index.insert(QLatin1String("propertyName"), QLatin1String("foobar"));
            index.insert(QLatin1String("propertyType"), QLatin1String("string"));
            indexes.append(index);
        }
        QJsonDbWriteRequest writeRequest;
        writeRequest.setObjects(indexes);
        mConnection->send(&writeRequest);
        waitForResponse(&writeRequest);
        QVERIFY(!mRequestErrors.contains(&writeRequest));
    }

    // query on one of the indexes
    {
        QJsonDbReadRequest readRequest;
        readRequest.setQuery(QLatin1String("[?_type=\"duck\"][/closeIndexesTest2]"));
        mConnection->send(&readRequest);
        waitForResponse(&readRequest);
        QList<QJsonObject> results = readRequest.takeResults();
        QCOMPARE(results.count(), 1);
    }

    // close indexes
    kill(mProcess->pid(), SIGUSR1);

    // query again
    {
        QJsonDbReadRequest readRequest;
        readRequest.setQuery(QLatin1String("[?_type=\"duck\"][/closeIndexesTest2]"));
        mConnection->send(&readRequest);
        waitForResponse(&readRequest);
        QList<QJsonObject> results = readRequest.takeResults();
        QCOMPARE(results.count(), 1);
    }
}

void TestQJsonDbRequest::removablePartition()
{
#ifdef Q_OS_LINUX
    if (geteuid())
        QSKIP("This test only works as root");

    if (!(QFile::exists(QLatin1String("/sbin/mkfs.ext2")) || QFile::exists(QLatin1String("/sbin/mkfs"))))
        QSKIP("This test requires mkfs.ext2 or mkfs");

    // create a notification on Partitions
    QJsonDbWatcher watcher;
    watcher.setPartition(QLatin1String("Ephemeral"));
    watcher.setQuery("[?_type=\"Partition\"]");
    mConnection->addWatcher(&watcher);
    waitForStatus(&watcher, QJsonDbWatcher::Active);

    QJsonObject def;
    def.insert(QStringLiteral("name"), QStringLiteral("removableTest"));
    def.insert(QStringLiteral("path"), QStringLiteral("/mnt/removablePartition"));
    def.insert(QStringLiteral("removable"), true);

    QJsonArray defs;
    defs.append(def);

    // ensure that the new file is written to the same directory as the main partitions.json
    QFile partitionsFile(QFileInfo(QFINDTESTDATA("partitions.json")).absoluteDir().absoluteFilePath(QLatin1String("partitions-test.json")));
    partitionsFile.open(QFile::WriteOnly);
    partitionsFile.write(QJsonDocument(defs).toJson());
    partitionsFile.close();

    QDir mnt(def.value(QStringLiteral("path")).toString());

    // unmount just in case previous run failed
    system(QString::fromLatin1("umount -l %1 > /dev/null 2>&1").arg(mnt.absolutePath()).toLatin1());

    // load the partitions via a SIGHUP and wait for the notification
    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 1));
    QList<QJsonDbNotification> notifications = watcher.takeNotifications();
    QCOMPARE(notifications.count(), 1);

    QJsonObject newPartition = notifications.at(0).object();
    QCOMPARE(newPartition.value(QStringLiteral("name")).toString(),
             def.value(QStringLiteral("name")).toString());
    QCOMPARE(newPartition.value(QStringLiteral("path")).toString(),
             def.value(QStringLiteral("path")).toString());
    QVERIFY(!newPartition.value(QStringLiteral("available")).toBool());

    // add a watcher on the partition
    QJsonDbWatcher watcher2;
    watcher2.setPartition(def.value(QStringLiteral("name")).toString());
    watcher2.setQuery(QStringLiteral("[?_type=\"removable-test\"]"));
    mConnection->addWatcher(&watcher2);
    waitForStatus(&watcher2, QJsonDbWatcher::Active);

    // make sure the partition doesn't work
    QJsonObject o;
    o.insert(QStringLiteral("_type"), QStringLiteral("removable-test"));
    QJsonDbCreateRequest write(o);

    write.setPartition(def.value(QStringLiteral("name")).toString());
    mConnection->send(&write);
    waitForResponse(&write);
    QVERIFY(mRequestErrors.contains(&write));
    QCOMPARE(mRequestErrors[&write], QJsonDbRequest::PartitionUnavailable);
    mRequestErrors.clear();

    // dd a file to use with our loopback device
    QString tmpFile = QStringLiteral("/tmp/removablePartition.img");
    QVERIFY(system(QString::fromLatin1("dd if=/dev/zero of=%1 bs=1024 count=512 > /dev/null 2>&1").arg(tmpFile).toLatin1()) == 0);
    if (QFile::exists(QLatin1String("/sbin/mkfs")))
        QVERIFY(system(QString::fromLatin1("mkfs -F -T ext2 %1 > /dev/null 2>&1").arg(tmpFile).toLatin1()) == 0);
    else
        QVERIFY(system(QString::fromLatin1("mkfs.ext2 -F -T ext2 %1 > /dev/null 2>&1").arg(tmpFile).toLatin1()) == 0);

    // mount
    QVERIFY(mnt.mkpath(QStringLiteral(".")));
    QVERIFY(system(QString::fromLatin1("mount -o loop %1 %2 > /dev/null 2>&1").arg(tmpFile).arg(mnt.absolutePath()).toLatin1()) == 0);

    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 1));
    notifications = watcher.takeNotifications();
    QCOMPARE(notifications.count(), 1);

    QJsonObject updatedPartition = notifications.at(0).object();
    QCOMPARE(updatedPartition.value(QStringLiteral("name")).toString(),
             def.value(QStringLiteral("name")).toString());
    QCOMPARE(updatedPartition.value(QStringLiteral("path")).toString(),
             def.value(QStringLiteral("path")).toString());
    QVERIFY(updatedPartition.value(QStringLiteral("available")).toBool());

    // make sure the partition works
    mConnection->send(&write);
    waitForResponseAndNotifications(&write, &watcher2, 1);
    QVERIFY(!mRequestErrors.contains(&write));
    notifications = watcher2.takeNotifications();
    QCOMPARE(notifications.size(), 1);

    // unmount
    QVERIFY(system(QString::fromLatin1("umount -l %1 > /dev/null 2>&1").arg(mnt.absolutePath()).toLatin1()) == 0);

    // remove the mount point
    QVERIFY(mnt.rmpath(QStringLiteral(".")));

    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 1));
    notifications = watcher.takeNotifications();
    QCOMPARE(notifications.count(), 1);

    updatedPartition = notifications.at(0).object();
    QCOMPARE(updatedPartition.value(QStringLiteral("name")).toString(),
             def.value(QStringLiteral("name")).toString());
    QCOMPARE(updatedPartition.value(QStringLiteral("path")).toString(),
             def.value(QStringLiteral("path")).toString());
    QVERIFY(!updatedPartition.value(QStringLiteral("available")).toBool());

    // make sure the partition doesn't work
    mConnection->send(&write);
    waitForResponse(&write);
    QVERIFY(mRequestErrors.contains(&write));
    QCOMPARE(mRequestErrors[&write], QJsonDbRequest::PartitionUnavailable);

    // remove the partition definition and reload
    partitionsFile.remove();
    kill(mProcess->pid(), SIGHUP);
    QVERIFY(waitForResponseAndNotifications(0, &watcher, 1));

    mConnection->removeWatcher(&watcher);
    waitForStatus(&watcher, QJsonDbWatcher::Inactive);
    mConnection->removeWatcher(&watcher2);
    waitForStatus(&watcher2, QJsonDbWatcher::Inactive);

    // remove the tmp file
    QFile::remove(tmpFile);
#endif
}

/*!
    Write one object with the _type "test" and the value \a value into the database.
*/
bool TestQJsonDbRequest::writeTestObject(QObject* parent, const QString &type, int value, const QString &partition)
{
    // -- write one object
    QJsonDbObject obj;
    obj.insert(typeStr(), QJsonValue(type));
    obj.insert(QStringLiteral("val"), QJsonValue(value));

    QJsonDbCreateRequest *req1 = new QJsonDbCreateRequest(obj, parent);
    req1->setPartition(partition);
    mConnection->send(req1);
    return waitForResponse(req1);
}

/*!
    Simple test, just writing and reading from the database.
    This is the most basic test.
*/
void TestQJsonDbRequest::writeAndRemove()
{
    QVERIFY(mConnection);

    // -- write one object
    QObject parent;
    QVERIFY(writeTestObject(&parent, QStringLiteral("writeRemoveTest"), 0));

    // -- read one object
    QJsonDbReadRequest req2(QString("[?_type=\"writeRemoveTest\"]"));
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));
    QVERIFY(!mRequestErrors.contains(&req2));

    QList<QJsonObject> results = req2.takeResults();
    QCOMPARE(results.count(), 1);
    QJsonObject obj = results.takeFirst();
    QCOMPARE(obj.value(typeStr()).toString(), QStringLiteral("writeRemoveTest"));
    QCOMPARE(obj.value(QStringLiteral("val")), QJsonValue(0));
}

/*!
    Checking that queue handling with several writes at the same time works.
*/
void TestQJsonDbRequest::severalWrites()
{
    QVERIFY(mConnection);

    QObject parent;
    const int numRequests = 300;
    QList<QJsonDbRequest *> pendingRequests;

    // -- Create and send the write requests
    for (int i = 0; i < numRequests; i++) {
        QJsonObject obj;
        obj.insert(typeStr(), QJsonValue(QStringLiteral("test")));
        obj.insert(QStringLiteral("_uuid"), QJsonDbObject::createUuid().toString());
        obj.insert(QStringLiteral("val"), QJsonValue(QString::number(i)));

        QJsonDbCreateRequest *req1 = new QJsonDbCreateRequest(obj, &parent);
        mConnection->send(req1);
        pendingRequests << req1;
    }

    QVERIFY(waitForResponse(pendingRequests));
    QVERIFY(mRequestErrors.isEmpty());

    // -- read one object
    QJsonDbReadRequest req2(QString("[?_type=\"test\"]"));
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));
    QVERIFY(!mRequestErrors.contains(&req2));

    QList<QJsonObject> results = req2.takeResults();
    QCOMPARE(results.count(), numRequests);
    QJsonObject obj = results.takeFirst();
    QCOMPARE(obj.value(typeStr()).toString(), QStringLiteral("test"));
}

void TestQJsonDbRequest::readRequest_data()
{
    QTest::addColumn<QString>("partition");

    QTest::newRow("default") << "";
    QTest::newRow("private") << "Private";
}

/*!
    In depth checking of read request.
*/
void TestQJsonDbRequest::readRequest()
{
    QVERIFY(mConnection);
    QFETCH(QString, partition);

    QJsonDbReadRequest req2(QString("[?_type=\"hallo\"]"));

    // -- check query property
    QCOMPARE(req2.query(), QString("[?_type=\"hallo\"]"));
    req2.setQuery(QString("[?_type=\"%1\"]"));
    QCOMPARE(req2.query(), QString("[?_type=\"%1\"]"));

    // -- try to send a query with no query field
    req2.setQuery(QString());
    req2.setPartition(partition);
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));

    QCOMPARE(req2.status(), QJsonDbRequest::Error);
    QVERIFY(mRequestErrors.contains(&req2));
    QCOMPARE(mRequestErrors[&req2], QJsonDbRequest::MissingQuery);

    // -- check bind values
    QJsonDbReadRequest req3;
    req3.setQuery(QStringLiteral("[?_type=%1]"));

    QJsonValue value = req3.boundValue("1");
    QVERIFY(value.isUndefined());

    req3.bindValue("1", QJsonValue(QStringLiteral("readTest")));
    value = req3.boundValue("1");
    QVERIFY(value.isString());
    QCOMPARE(value.toString(), QStringLiteral("readTest"));

    req3.clearBoundValues();
    value = req3.boundValue("1");
    QVERIFY(value.isUndefined());

    // - rebind
    req3.bindValue("1", QJsonValue(QStringLiteral("readTest2")));
    value = req3.boundValue("1");
    QVERIFY(value.isString());
    QCOMPARE(value.toString(), QString("readTest2"));

    // -- check queryLimit
    QCOMPARE(req3.queryLimit(), -1);
    req3.setQueryLimit(42);
    QCOMPARE(req3.queryLimit(), 42);
    req3.setQueryLimit(2);
    QCOMPARE(req3.queryLimit(), 2);

    // -- check status
    QCOMPARE(req3.status(), QJsonDbRequest::Inactive);
    req3.setPartition(partition);
    mConnection->send(&req3);
    QVERIFY(req3.status() != QJsonDbRequest::Inactive);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));

    // -- no object returned
    QList<QJsonObject> results = req3.takeResults();
    QCOMPARE(results.count(), 0);

    // -- write one object and re-read
    QObject parent;
    QVERIFY(writeTestObject(&parent, QStringLiteral("readTest2"), 0, partition));
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));

    results = req3.takeResults();
    QCOMPARE(results.count(), 1);
    QJsonObject obj = results.takeFirst();
    QCOMPARE(obj.value(typeStr()).toString(), QStringLiteral("readTest2"));
    QCOMPARE(obj.value(QStringLiteral("val")), QJsonValue(0));

    // -- write another object and re-read
    QVERIFY(writeTestObject(&parent, QStringLiteral("readTest2"), 1, partition));
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));

    results = req3.takeResults();
    QCOMPARE(results.count(), 2);

    // -- check sortKey
    QCOMPARE(req3.sortKey(), typeStr());

    req3.setQuery(QStringLiteral("[?_type=%1][/_uuid]"));
    req3.bindValue(QStringLiteral("1"), QStringLiteral("readTest2"));
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));
    QCOMPARE(req3.sortKey(), uuidStr());
}

void TestQJsonDbRequest::writeRequest_data()
{
    QTest::addColumn<QString>("partition");

    QTest::newRow("default") << "";
    QTest::newRow("private") << "Private";
}

/*!
    In depth checking of write request.
*/
void TestQJsonDbRequest::writeRequest()
{
    QVERIFY(mConnection);
    QFETCH(QString, partition);

    QJsonObject obj;
    obj.insert(typeStr(), QJsonValue(QStringLiteral("writeTest")));
    obj.insert(QStringLiteral("val"), QJsonValue(0));
    obj.insert(QStringLiteral("_deleted"), true);

    QJsonDbWriteRequest req1;
    QCOMPARE(req1.status(), QJsonDbRequest::Inactive);

    // try to send an object without uuid and since it's a remove
    // it'll fail
    req1.setObjects(QList<QJsonObject>() << obj);
    req1.setPartition(partition);
    mConnection->send(&req1);
    QVERIFY(waitForResponse(&req1));

    QCOMPARE(req1.status(), QJsonDbRequest::Error);
    QVERIFY(mRequestErrors.contains(&req1));
    QCOMPARE(mRequestErrors[&req1], QJsonDbRequest::MissingUUID);
    mRequestErrors.clear();

    // try to send no objects
    req1.setObjects(QList<QJsonObject>());
    mConnection->send(&req1);
    QVERIFY(waitForResponse(&req1));

    QCOMPARE(req1.status(), QJsonDbRequest::Error);
    QVERIFY(mRequestErrors.contains(&req1));
    QCOMPARE(mRequestErrors[&req1], QJsonDbRequest::MissingObject);
    mRequestErrors.clear();

    // try to send an object without type
    obj.remove(typeStr());
    obj.remove(QStringLiteral("_deleted"));
    req1.setObjects(QList<QJsonObject>() << obj);
    mConnection->send(&req1);
    QVERIFY(waitForResponse(&req1));

    QCOMPARE(req1.status(), QJsonDbRequest::Error);
    QVERIFY(mRequestErrors.contains(&req1));
    QCOMPARE(mRequestErrors[&req1], QJsonDbRequest::MissingType);
    mRequestErrors.clear();
}

void TestQJsonDbRequest::createRequest_data()
{
    QTest::addColumn<QString>("partition");

    QTest::newRow("default") << "";
    QTest::newRow("private") << "Private";
}

void TestQJsonDbRequest::createRequest()
{
    QVERIFY(mConnection);
    QFETCH(QString, partition);

    // -- write one object
    QJsonObject obj;
    obj.insert(typeStr(), QJsonValue(QStringLiteral("createTest")));
    obj.insert(QStringLiteral("val"), QJsonValue(QStringLiteral("test2")));

    QJsonDbCreateRequest req1(obj);
    req1.setPartition(partition);
    mConnection->send(&req1);
    QVERIFY(waitForResponse(&req1));
    QVERIFY(!mRequestErrors.contains(&req1));

    // - check that we have results of the create. The results just have a uuid and a version.
    QList<QJsonObject> results = req1.takeResults();
    QCOMPARE(results.count(), 1);
    obj = results.takeFirst();
    QVERIFY(!obj.value(uuidStr()).toString().isEmpty());
    QVERIFY(!obj.value(versionStr()).toString().isEmpty());

    // -- reuse the old request to write a couple more objects
    const int numObjects = 300;

    QList<QJsonObject> list;
    for (int i = 0; i < numObjects; i++) {
        QJsonObject obj;
        obj.insert(typeStr(), QJsonValue(QStringLiteral("createTest")));
        obj.insert(QStringLiteral("val"), QJsonValue(i));

        list << obj;
    }
    req1.setObjects(list);
    mConnection->send(&req1);
    QVERIFY(waitForResponse(&req1));
    QVERIFY(!mRequestErrors.contains(&req1));

    // -- read the objects
    QJsonDbReadRequest req2(QString("[?_type=\"createTest\"]"));
    req2.setPartition(partition);
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));
    QVERIFY(!mRequestErrors.contains(&req2));

    results = req2.takeResults();
    QCOMPARE(results.count(), numObjects + 1);
    obj = results.takeFirst();
    QCOMPARE(obj.value(typeStr()).toString(), QStringLiteral("createTest"));
}

void TestQJsonDbRequest::updateRequest_data()
{
    QTest::addColumn<QString>("partition");

    QTest::newRow("default") << "";
    QTest::newRow("private") << "Private";
}

void TestQJsonDbRequest::updateRequest()
{
    QVERIFY(mConnection);
    QFETCH(QString, partition);

    // -- write one object
    QObject parent;
    QVERIFY(writeTestObject(&parent, QStringLiteral("updateTest"), 0, partition));

    // -- read one object
    QJsonDbReadRequest req2(QString("[?_type=\"updateTest\"]"));
    req2.setPartition(partition);
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));
    QVERIFY(!mRequestErrors.contains(&req2));

    QList<QJsonObject> results = req2.takeResults();
    QCOMPARE(results.count(), 1);

    // -- update the object
    QJsonObject obj1(results.takeFirst());
    obj1.insert(QStringLiteral("val"), QJsonValue(1));
    results.append(obj1);

    QJsonDbUpdateRequest req3(results);
    req3.setPartition(partition);
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));

    // - check that we have results of the update. The results just have a uuid and a version.
    results = req3.takeResults();
    QCOMPARE(results.count(), 1);
    QJsonObject obj = results.takeFirst();
    QVERIFY(!obj.value(uuidStr()).toString().isEmpty());
    QVERIFY(!obj.value(versionStr()).toString().isEmpty());

    // - re-read and check if really updated also in the database
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));
    QVERIFY(!mRequestErrors.contains(&req2));

    results = req2.takeResults();
    QCOMPARE(results.count(), 1);
    obj = results.takeFirst();
    QCOMPARE(obj.value(QStringLiteral("val")), QJsonValue(1)); // this is the updated value

    // -- update from null
    obj.insert(typeStr(), QJsonValue(QStringLiteral("new")));
    obj.insert(QStringLiteral("_uuid"), QJsonDbObject::createUuid().toString());
    req3.setObjects(QList<QJsonObject>() << obj);
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));
}

void TestQJsonDbRequest::privatePartition()
{
    QJsonObject contact1;
    contact1.insert(QStringLiteral("_type"), QStringLiteral("test-contact"));
    contact1.insert(QStringLiteral("_uuid"), QUuid::createUuid().toString());
    contact1.insert(QStringLiteral("name"), QStringLiteral("Joe"));
    QJsonObject contact2;
    contact2.insert(QStringLiteral("_type"), QStringLiteral("test-contact"));
    contact2.insert(QStringLiteral("_uuid"), QUuid::createUuid().toString());
    contact2.insert(QStringLiteral("name"), QStringLiteral("Alice"));

    QJsonDbWriteRequest write;
    write.setObjects(QList<QJsonObject>() << contact1 << contact2);
    // use the explicit form of the private partition (with full username)
    write.setPartition(QString::fromLatin1("%1.Private").arg(QJsonDbStandardPaths::currentUser()));
    mConnection->send(&write);
    QVERIFY(waitForResponse(&write));
    QVERIFY(!mRequestErrors.contains(&write));
    QList<QJsonObject> results = write.takeResults();
    QCOMPARE(results.count(), 2);
    contact1.insert(QStringLiteral("_version"), results[0].value(QStringLiteral("_version")));
    contact2.insert(QStringLiteral("_version"), results[1].value(QStringLiteral("_version")));

    QJsonDbReadRequest query;
    query.setQuery(QStringLiteral("[?_type=%type][/_type]"));
    query.bindValue(QStringLiteral("type"), QStringLiteral("test-contact"));

    // use the default form of private partition (no username specified, default to current user)
    query.setPartition(QStringLiteral("Private"));
    mConnection->send(&query);
    QVERIFY(waitForResponse(&query));
    QVERIFY(!mRequestErrors.contains(&query));
    QCOMPARE(query.sortKey(), QStringLiteral("_type"));

    quint32 state = query.stateNumber();
    QVERIFY(state != 0);

    results = query.takeResults();
    QCOMPARE(results.count(), 2);
    foreach (const QJsonObject &object, results) {
        QVERIFY(object.value(QStringLiteral("_uuid")).toString() == contact1.value(QStringLiteral("_uuid")).toString() ||
                object.value(QStringLiteral("_uuid")).toString() == contact2.value(QStringLiteral("_uuid")).toString());
    }

    contact1.insert(QStringLiteral("_deleted"), true);
    contact2.insert(QStringLiteral("name"), QStringLiteral("Jane"));
    write.setObjects(QList<QJsonObject>() << contact1 << contact2);
    mConnection->send(&write);
    QVERIFY(waitForResponse(&write));
    QVERIFY(!mRequestErrors.contains(&write));
    results = write.takeResults();
    QCOMPARE(results.count(), 2);
    contact1.insert(QStringLiteral("_version"), results[0].value(QStringLiteral("_version")));
    contact2.insert(QStringLiteral("_version"), results[1].value(QStringLiteral("_version")));

    mConnection->send(&query);
    QVERIFY(waitForResponse(&query));
    QVERIFY(!mRequestErrors.contains(&query));
    QVERIFY(query.stateNumber() > state);
    state = query.stateNumber();

    results = query.takeResults();
    QCOMPARE(results.count(), 1);
    QCOMPARE(results[0].value(QStringLiteral("_uuid")).toString(), contact2.value(QStringLiteral("_uuid")).toString());
    QCOMPARE(results[0].value(QStringLiteral("name")).toString(), contact2.value(QStringLiteral("name")).toString());

    // switch
    query.setPartition(QString::fromLatin1("%1.Private").arg(QJsonDbStandardPaths::currentUser()));
    write.setPartition(QStringLiteral("Private"));

    contact2.insert(QStringLiteral("_deleted"), true);
    write.setObjects(QList<QJsonObject>() << contact2);
    mConnection->send(&write);
    QVERIFY(waitForResponse(&write));
    QVERIFY(!mRequestErrors.contains(&write));

    mConnection->send(&query);
    QVERIFY(waitForResponse(&query));
    QVERIFY(!mRequestErrors.contains(&query));
    QVERIFY(query.stateNumber() > state);

    results = query.takeResults();
    QVERIFY(results.isEmpty());
}

void TestQJsonDbRequest::privatePartition2()
{
    QJsonDbObject contact1;
    contact1.insert(QStringLiteral("_uuid"), QStringLiteral("{ed3d2c73-27f6-4443-9945-3b18b11d7c56}"));
    contact1.insert(QStringLiteral("_type"), QStringLiteral("privatePartition2"));
    contact1.insert(QStringLiteral("name"), QStringLiteral("Joe"));
    QJsonDbObject contact2;
    contact2.insert(QStringLiteral("_type"), QStringLiteral("privatePartition2"));
    contact2.insert(QStringLiteral("_uuid"), QStringLiteral("{6ec6277b-0020-4fa6-a40f-02e574b3af6a}"));
    contact2.insert(QStringLiteral("name"), QStringLiteral("Alice"));

    QJsonDbWriteRequest write1;
    write1.setObjects(QList<QJsonObject>() << contact1);
    write1.setPartition(QStringLiteral("Private"));
    QJsonDbWriteRequest write2;
    write2.setObjects(QList<QJsonObject>() << contact2);
    write2.setPartition(QStringLiteral("Private"));
    QJsonDbReadRequest read(QStringLiteral("[?_type=\"privatePartition2\"]"));
    read.setPartition(QStringLiteral("Private"));
    mConnection->send(&write1);
    mConnection->send(&write2);
    mConnection->send(&read);

    QVERIFY(waitForResponse(&write2));
    QVERIFY(!mRequestErrors.contains(&write1));
    QVERIFY(!mRequestErrors.contains(&write2));
    QList<QJsonObject> results = write2.takeResults();
    QCOMPARE(results.count(), 1);
    QCOMPARE(results.at(0).value(QStringLiteral("_uuid")).toString(), contact2.value(QStringLiteral("_uuid")).toString());

    QVERIFY(waitForResponse(&read));
    results = read.takeResults();
    QCOMPARE(results.size(), 2);
    QList<QJsonDbRequest::Status> statuses = mRequestStatuses.value(&write2);
    QCOMPARE(statuses.size(), 3);
    QCOMPARE((int)statuses.at(0), (int)QJsonDbRequest::Sent);
    QCOMPARE((int)statuses.at(1), (int)QJsonDbRequest::Receiving);
    QCOMPARE((int)statuses.at(2), (int)QJsonDbRequest::Finished);
}

void TestQJsonDbRequest::privatePartitions()
{
    QJsonDbObject contact1;
    contact1.insert(QStringLiteral("_uuid"), QStringLiteral("{9a57c619-fa16-4259-acf5-7d670f59674f}"));
    contact1.insert(QStringLiteral("_type"), QStringLiteral("privatePartitions"));
    contact1.insert(QStringLiteral("name"), QStringLiteral("Joe"));
    QJsonDbObject contact2;
    contact2.insert(QStringLiteral("_type"), QStringLiteral("privatePartitions"));
    contact2.insert(QStringLiteral("_uuid"), QStringLiteral("{d87707c5-71ae-4524-813e-4dd9dda55a87}"));
    contact2.insert(QStringLiteral("name"), QStringLiteral("Alice"));

    QJsonDbWriteRequest write1;
    write1.setObjects(QList<QJsonObject>() << contact1);
    write1.setPartition(QStringLiteral("joe.Private"));
    mConnection->send(&write1);
    QVERIFY(waitForResponse(&write1));

    QJsonDbWriteRequest write2;
    write2.setObjects(QList<QJsonObject>() << contact2);
    write2.setPartition(QStringLiteral("alice.Private"));
    mConnection->send(&write2);
    QVERIFY(waitForResponse(&write2));

    {
        QJsonDbReadRequest read(QStringLiteral("[?_type=\"privatePartitions\"]"));
        read.setPartition(QStringLiteral("Private"));
        mConnection->send(&read);
        QVERIFY(waitForResponse(&read));
        QList<QJsonObject> results = read.takeResults();
        QCOMPARE(results.size(), 0);
    }
    {
        QJsonDbReadRequest read(QStringLiteral("[?_type=\"privatePartitions\"]"));
        read.setPartition(QStringLiteral("alice.Private"));
        mConnection->send(&read);
        QVERIFY(waitForResponse(&read));
        QList<QJsonObject> results = read.takeResults();
        QCOMPARE(results.size(), 1);
        QCOMPARE(results.at(0).value(QStringLiteral("name")).toString(), QLatin1String("Alice"));
    }
    {
        QJsonDbReadRequest read(QStringLiteral("[?_type=\"privatePartitions\"]"));
        read.setPartition(QStringLiteral("joe.Private"));
        mConnection->send(&read);
        QVERIFY(waitForResponse(&read));
        QList<QJsonObject> results = read.takeResults();
        QCOMPARE(results.size(), 1);
        QCOMPARE(results.at(0).value(QStringLiteral("name")).toString(), QLatin1String("Joe"));
    }
}

void TestQJsonDbRequest::invalidPrivatePartition()
{
    QJsonObject contact1;
    contact1.insert(QStringLiteral("_type"), QStringLiteral("test-contact"));
    contact1.insert(QStringLiteral("_uuid"), QUuid::createUuid().toString());
    contact1.insert(QStringLiteral("name"), QStringLiteral("Joe"));

    QJsonDbWriteRequest write;
    write.setObjects(QList<QJsonObject>() << contact1);
    write.setPartition(QStringLiteral("userthatdoesnotexist.Private"));
    mConnection->send(&write);
    waitForResponse(&write);
    QVERIFY(mRequestErrors.contains(&write));
    QCOMPARE(mRequestErrors[&write], QJsonDbRequest::InvalidPartition);
}

/*!
    Check if removing an object works and throws errors if it doesn't work.
*/
void TestQJsonDbRequest::removeRequest()
{
    QVERIFY(mConnection);

    // -- write some objects
    QObject parent;
    writeTestObject(&parent, QStringLiteral("removeTest"), 0);
    writeTestObject(&parent, QStringLiteral("removeTest"), 1);
    writeTestObject(&parent, QStringLiteral("removeTest"), 2);
    writeTestObject(&parent, QStringLiteral("removeTest"), 3);

    // -- read the objects
    QJsonDbReadRequest req2(QString("[?_type=\"removeTest\"]"));
    mConnection->send(&req2);
    QVERIFY(waitForResponse(&req2));

    QList<QJsonObject> results = req2.takeResults();
    QCOMPARE(results.count(), 4);

    QJsonDbRemoveRequest req3(results);

    // try to delete one object
    QJsonObject toDelete = results[0];
    req3.setObjects(QList<QJsonObject>() << toDelete );
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QList<QJsonObject> writeResults = req3.takeResults();
    QCOMPARE(writeResults.size(), 1);
    QCOMPARE(req3.status(), QJsonDbRequest::Finished);
    toDelete.insert(QStringLiteral("_version"), writeResults.at(0).value(QStringLiteral("_version")).toString());

    // try to delete an object again. It's a replay, not an error?
    req3.setObjects(QList<QJsonObject>() << toDelete );
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(!mRequestErrors.contains(&req3));
    QCOMPARE(req3.status(), QJsonDbRequest::Finished);

    QJsonObject obj;
    obj.insert(typeStr(), QJsonValue(QStringLiteral("removeTest")));

    // try to delete an object without uuid
    QJsonDbRemoveRequest req4(QList<QJsonObject>() << obj);
    mConnection->send(&req4);
    QVERIFY(waitForResponse(&req4));
    QVERIFY(mRequestErrors.contains(&req4));
    QCOMPARE(req4.status(), QJsonDbRequest::Error);
    QCOMPARE(mRequestErrors.value(&req4), QJsonDbRequest::MissingUUID);

    // try to delete no objects
    req3.setObjects(QList<QJsonObject>());
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(mRequestErrors.contains(&req3));
    QCOMPARE(req3.status(), QJsonDbRequest::Error);
    QCOMPARE(mRequestErrors.value(&req3), QJsonDbRequest::MissingObject);

    // try to delete an object without type
    obj.remove(typeStr());
    obj.insert(uuidStr(), results[0].value(uuidStr()));
    req3.setObjects(QList<QJsonObject>() << obj);
    mConnection->send(&req3);
    QVERIFY(waitForResponse(&req3));
    QVERIFY(mRequestErrors.contains(&req3));
    QCOMPARE(req3.status(), QJsonDbRequest::Error);
    QCOMPARE(mRequestErrors.value(&req3), QJsonDbRequest::MissingType);

}

void TestQJsonDbRequest::forced()
{
    QJsonDbObject item;
    item.setUuid(QJsonDbObject::createUuid());
    item.insert(QStringLiteral("_type"), QStringLiteral("forcedTest"));
    item.insert(QStringLiteral("name"), QStringLiteral("Alice"));
    QJsonDbCreateRequest create(item);
    mConnection->send(&create);
    QVERIFY(waitForResponse(&create));
    QVERIFY(!mRequestErrors.contains(&create));

    // this should get rejected...no _version specified
    item.insert(QStringLiteral("name"), QStringLiteral("Joe"));
    QJsonDbWriteRequest update;
    update.setObjects(QList<QJsonObject>() << item);
    mConnection->send(&update);
    QVERIFY(waitForResponse(&update));
    QVERIFY(mRequestErrors.contains(&update));
    QCOMPARE(mRequestErrors[&update], QJsonDbRequest::UpdatingStaleVersion);
    mRequestErrors.clear();

    // force the write
    update.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&update);
    QVERIFY(waitForResponse(&update));
    QVERIFY(!mRequestErrors.contains(&update));

    // fail with a stale remove
    QJsonDbRemoveRequest remove(item);
    mConnection->send(&remove);
    QVERIFY(waitForResponse(&remove));
    QVERIFY(mRequestErrors.contains(&remove));
    QCOMPARE(mRequestErrors[&remove], QJsonDbRequest::UpdatingStaleVersion);
    mRequestErrors.clear();

    // force the remove
    remove.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&remove);
    QVERIFY(waitForResponse(&remove));
    QVERIFY(!mRequestErrors.contains(&remove));

    // make sure it's really gone
    QJsonDbReadObjectRequest read(item.uuid());
    mConnection->send(&read);
    QVERIFY(waitForResponse(&read));
    QVERIFY(read.takeResults().isEmpty());
}

void TestQJsonDbRequest::replaceFromNull()
{
    QJsonDbObject object;
    object.setUuid(QUuid::createUuid());
    object.insert(QLatin1String("_type"), QLatin1String("replaceFromNull"));
    object.insert(QLatin1String("bar"), QLatin1String("Julia"));

    QJsonDbUpdateRequest replace(object);
    replace.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&replace);
    QVERIFY(waitForResponse(&replace));

    // now read the object, it should be there
    QJsonDbReadRequest read;
    read.setQuery(QStringLiteral("[?_type=\"replaceFromNull\"]"));
    mConnection->send(&read);
    QVERIFY(waitForResponse(&read));
    QCOMPARE((int)read.status(), (int)QJsonDbReadRequest::Finished);
    QList<QJsonObject> results = read.takeResults();
    QCOMPARE(results.size(), 1);
}

void TestQJsonDbRequest::multiplerequests()
{
    QJsonDbObject object;
    object.setUuid(QUuid::createUuid());
    object.insert(QLatin1String("_type"), QLatin1String("multiplerequests"));
    object.insert(QLatin1String("bar"), QLatin1String("Julia"));

    {
        QJsonDbCreateRequest request(object);
        mConnection->send(&request);
        QVERIFY(waitForResponse(&request));

        // now read the object, it should be there
        QJsonDbReadRequest read;
        read.setQuery(QStringLiteral("[?_type=\"multiplerequests\"]"));
        mConnection->send(&read);
        QVERIFY(waitForResponse(&read));
        QCOMPARE((int)read.status(), (int)QJsonDbReadRequest::Finished);
        QList<QJsonObject> results = read.takeResults();
        QCOMPARE(results.size(), 1);
    }

    QJsonDbRemoveRequest remove1(object);
    remove1.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&remove1);

    QJsonDbUpdateRequest update(object);
    update.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&update);

    QJsonDbRemoveRequest remove2(object);
    remove2.setConflictResolutionMode(QJsonDbWriteRequest::Replace);
    mConnection->send(&remove2);

    QList<QJsonDbRequest *> requests;
    requests << &remove1 << &update << &remove2;
    QVERIFY(waitForResponse(requests));

    // now read the object, it shouldn't exist
    QJsonDbReadRequest read;
    read.setQuery(QStringLiteral("[?_type=\"multiplerequests\"]"));
    mConnection->send(&read);
    QVERIFY(waitForResponse(&read));
    QCOMPARE((int)read.status(), (int)QJsonDbReadRequest::Finished);
    QList<QJsonObject> results = read.takeResults();
    QCOMPARE(results.size(), 0);
}

void TestQJsonDbRequest::defaultConnection()
{
    // make sure that the default connection connects automatically
    QJsonDbConnection *connection = QJsonDbConnection::defaultConnection();
    QJsonDbReadRequest request(QStringLiteral("[?_type=\"Foo\"]"));
    QEventLoop ev;
    QObject::connect(&request, SIGNAL(finished()), &ev, SLOT(quit()));
    QTimer::singleShot(10000, &ev, SLOT(quit()));
    QVERIFY(connection->send(&request));
    ev.exec();
    QCOMPARE((int)request.status(), (int)QJsonDbRequest::Finished);
}

void TestQJsonDbRequest::privatePartitionFlushRequest()
{
    QJsonDbFlushRequest request;
    request.setPartition(QStringLiteral("Private"));
    QVERIFY(mConnection->send(&request));
    QVERIFY(waitForResponse(&request));
    QVERIFY(mRequestStatuses.contains(&request));
    QList<QtJsonDb::QJsonDbRequest::Status> statuses = mRequestStatuses.value(&request);
    QCOMPARE(statuses.size(), 2);
    QCOMPARE((int)statuses.at(0), (int)QJsonDbRequest::Receiving);
    QCOMPARE((int)statuses.at(1), (int)QJsonDbRequest::Finished);
}

class Worker : public QObject
{
    Q_OBJECT
public:
    QString partitionName;
    int requestsCount;
    QTimer *t;
    Worker() : requestsCount(0) { }

public Q_SLOTS:
    void start()
    {
        send();
    }

    void send()
    {
        QJsonDbObject item;
        item.setUuid(QUuid::createUuid());
        item.insert(QStringLiteral("_type"), QStringLiteral("multipleThreads"));

        QThread *thread = QThread::currentThread();

        QJsonDbWriteRequest *write = new QJsonDbWriteRequest;
        write->setPartition(partitionName);
        write->setObject(item);
        QObject::connect(write, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
                         this, SLOT(requestError(QtJsonDb::QJsonDbRequest::ErrorCode,QString)));
        QObject::connect(write, SIGNAL(finished()), this, SLOT(writeRequestFinished()));
        QObject::connect(write, SIGNAL(finished()), write, SLOT(deleteLater()));
        QObject::connect(thread, SIGNAL(finished()), write, SLOT(deleteLater()));
        QJsonDbConnection::defaultConnection()->send(write);
        requestsCount++;

        QJsonDbReadRequest *read = new QJsonDbReadRequest;
        read->setPartition(partitionName);
        read->setQuery(QStringLiteral("[?_type=\"multipleThreads\"]"));
        QObject::connect(read, SIGNAL(error(QtJsonDb::QJsonDbRequest::ErrorCode,QString)),
                         this, SLOT(requestError(QtJsonDb::QJsonDbRequest::ErrorCode,QString)));
        QObject::connect(read, SIGNAL(finished()), this, SLOT(readRequestFinished()));
        QObject::connect(read, SIGNAL(finished()), this, SLOT(send()));
        QObject::connect(read, SIGNAL(finished()), read, SLOT(deleteLater()));
        QObject::connect(thread, SIGNAL(finished()), read, SLOT(deleteLater()));
        QJsonDbConnection::defaultConnection()->send(read);
        requestsCount++;
    }

    void writeRequestFinished()
    {
        QJsonDbWriteRequest *r = qobject_cast<QJsonDbWriteRequest *>(sender());
        QVERIFY(r != 0);
        QList<QJsonObject> results = r->takeResults();
        QCOMPARE(results.size(), 1);
    }

    void readRequestFinished()
    {
        QJsonDbReadRequest *r = qobject_cast<QJsonDbReadRequest *>(sender());
        QVERIFY(r != 0);
        QList<QJsonObject> results = r->takeResults();
        QVERIFY(results.size() >= 1);
    }

    void requestError(QtJsonDb::QJsonDbRequest::ErrorCode code, const QString &message)
    {
        if (partitionName != QLatin1String("userthatdoesnotexist.Private")) {
            QJsonDbRequest *r = qobject_cast<QJsonDbRequest *>(sender());
            qDebug() << "request failed" << partitionName << r << code << message;
            QVERIFY(false);
        }
    }

    void stop()
    {
        // uncomment me if you want to see how many requests each thread managed to push through
        //qDebug() << QThread::currentThread() << "is stopping. Requests count" << requestsCount;
    }

    void quit()
    {
        QThread::currentThread()->quit();
    }
};

void TestQJsonDbRequest::multipleThreads_data()
{
    QTest::addColumn<QStringList>("partitions");

    QTest::newRow("serverpartition") << (QStringList());
    QTest::newRow("private") << (QStringList() << QStringLiteral("Private"));
    QTest::newRow("private-multi")
            << (QStringList() << QStringLiteral("Private") << QStringLiteral("alice.Private"));
    QTest::newRow("private-multi-nonexistent")
            << (QStringList() << QStringLiteral("Private") << QStringLiteral("alice.Private") << QStringLiteral("userthatdoesnotexist.Private"));
}

void TestQJsonDbRequest::multipleThreads()
{
    QFETCH(QStringList, partitions);

    QList<QThread *> threads;
    static const int NumThreads = 3;
    for (int i = 0; i < NumThreads; ++i) {
        QThread *thread = new QThread;

        Worker *w = new Worker;
        QTimer *timer = new QTimer;
        timer->setInterval(1000 + qrand() % 2000);
        timer->moveToThread(thread);
        QObject::connect(thread, SIGNAL(started()), timer, SLOT(start()));
        QObject::connect(timer, SIGNAL(timeout()), w, SLOT(quit()));
        QObject::connect(timer, SIGNAL(timeout()), timer, SLOT(deleteLater()));

        if (!partitions.isEmpty())
            w->partitionName = partitions.at(i % partitions.size());
        w->moveToThread(thread);
        QObject::connect(thread, SIGNAL(started()), w, SLOT(start()));
        QObject::connect(thread, SIGNAL(finished()), w, SLOT(stop()));
        QObject::connect(thread, SIGNAL(finished()), w, SLOT(deleteLater()));

        w->t = timer;
        threads.append(thread);
    }

    foreach (QThread *t, threads)
        t->start();
    foreach (QThread *t, threads)
        t->wait();

    qDeleteAll(threads);
}

void TestQJsonDbRequest::readObjectRequest()
{
    QUuid uuid = QUuid::createUuid();
    QJsonDbObject item;
    item.setUuid(uuid);
    item.insert(QStringLiteral("_type"), QStringLiteral("readObjectRequest"));

    QJsonDbReadObjectRequest request;
    QSignalSpy availableSpy(&request, SIGNAL(objectAvailable(QJsonObject)));
    QSignalSpy unavailableSpy(&request, SIGNAL(objectUnavailable(QUuid)));

    // test non-existent object
    request.setUuid(uuid);
    QVERIFY(mConnection->send(&request));
    QVERIFY(waitForResponse(&request));
    QCOMPARE(availableSpy.count(), 0);
    QCOMPARE(unavailableSpy.count(), 1);
    QList<QVariant> args = unavailableSpy.takeFirst();
    QCOMPARE(args.size(), 1);
    QCOMPARE(args.at(0).value<QUuid>(), uuid);

    // create the object and try again
    {
        QJsonDbCreateRequest request(item);
        QVERIFY(mConnection->send(&request));
        QVERIFY(waitForResponse(&request));
    }
    QVERIFY(mConnection->send(&request));
    QVERIFY(waitForResponse(&request));
    QCOMPARE(availableSpy.count(), 1);
    QCOMPARE(unavailableSpy.count(), 0);
    args = availableSpy.takeFirst();
    QCOMPARE(args.size(), 1);
    QJsonObject result = args.at(0).value<QJsonObject>();
    QCOMPARE(result.value(QStringLiteral("_uuid")).toString(), item.uuid().toString());
    QCOMPARE(result.value(QStringLiteral("_type")).toString(), item.value(QStringLiteral("_type")).toString());
}

void TestQJsonDbRequest::bindings()
{
    {
        QJsonDbObject object;
        object.setUuid(QUuid::createUuid());
        object.insert(QLatin1String("_type"), QLatin1String("bindingstest"));
        object.insert(QLatin1String("foo"), QLatin1String("[?_type=\"bunny\"]"));
        object.insert(QLatin1String("bar"), QLatin1String("Julia"));
        QJsonDbCreateRequest request(object);
        mConnection->send(&request);
        waitForResponse(&request);
    }

    {
        QJsonDbReadRequest request;
        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?foo=%blah]"));
        request.bindValue(QLatin1String("blah"), QLatin1String("[?_type=\"bunny\"]"));
        mConnection->send(&request);
        waitForResponse(&request);
        QList<QJsonObject> results = request.takeResults();
        QCOMPARE(results.size(), 1);
        QCOMPARE(results.at(0).value(QLatin1String("_type")).toString(), QLatin1String("bindingstest"));
        QCOMPARE(results.at(0).value(QLatin1String("foo")).toString(), QLatin1String("[?_type=\"bunny\"]"));
    }

    {
        // first check that the real regexp works:
        QJsonDbReadRequest request;
        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?bar =~ \"/J*/wi\"]"));
        mConnection->send(&request);
        waitForResponse(&request);
        QList<QJsonObject> results = request.takeResults();
        QCOMPARE(results.size(), 1);

        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?bar=%blah]"));
        request.bindValue(QLatin1String("blah"), QLatin1String("~/J*/wi"));
        mConnection->send(&request);
        waitForResponse(&request);
        results = request.takeResults();
        QCOMPARE(results.size(), 0);

        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?bar=%blah]"));
        request.bindValue(QLatin1String("blah"), QLatin1String("~\"/J*/wi\""));
        mConnection->send(&request);
        waitForResponse(&request);
        results = request.takeResults();
        QCOMPARE(results.size(), 0);
    }

    {
        QJsonDbReadRequest request;
        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?bar =~ %blah]"));
        request.bindValue(QLatin1String("blah"), QLatin1String("/J*/wi"));
        mConnection->send(&request);
        waitForResponse(&request);
        QList<QJsonObject> results = request.takeResults();
        QCOMPARE(results.size(), 1);

        request.setQuery(QStringLiteral("[?_type=\"bindingstest\"][?bar =~ %blah]"));
        request.bindValue(QLatin1String("blah"), QLatin1String("/Z*/wi"));
        mConnection->send(&request);
        waitForResponse(&request);
        results = request.takeResults();
        QCOMPARE(results.size(), 0);
    }
}

class defaultPartition_helper
{
public:
    defaultPartition_helper(TestHelper *testHelper)
        : mTestHelper(testHelper)
    {
        // temporarily rename config files
        renameFiles(false);

        // add a Partitions watcher
        mWatcher.setPartition(QLatin1String("Ephemeral"));
        mWatcher.setQuery("[?_type=\"Partition\"]");
        mTestHelper->connection()->addWatcher(&mWatcher);
        mTestHelper->waitForStatus(&mWatcher, QtJsonDb::QJsonDbWatcher::Active);
    }

    ~defaultPartition_helper()
    {
        // restore original config file names
        renameFiles(true);

        // remove the Partitions watcher
        mTestHelper->connection()->removeWatcher(&mWatcher);
        mTestHelper->waitForStatus(&mWatcher, QtJsonDb::QJsonDbWatcher::Inactive);
    }

    // Replaces the current partition defs in the daemon with new ones. Returns the final partition defs as seen by the daemon.
    QList<QJsonObject> loadAndQueryPartitionDefs(const QJsonArray &defs)
    {
        // ensure that the new file is written to the same directory as the original partitions.json (which is now renamed!)
        QFile partitionsFile(QFileInfo(QFINDTESTDATA("partitions.json.bak")).absoluteDir().absoluteFilePath(QLatin1String("partitions-test.json")));
        partitionsFile.open(QFile::WriteOnly);
        partitionsFile.write(QJsonDocument(defs).toJson());
        partitionsFile.close();

        // make daemon reload partition defs
        mTestHelper->sighupDaemon();
        if (!mTestHelper->waitForResponseAndNotifications(0, &mWatcher, defs.size())) {
            QWARN("reloading partition defs failed");
            return QList<QJsonObject>();
        }
        partitionsFile.remove();

        // retrieve current partition defs
        QJsonDbReadRequest partitionQuery;
        partitionQuery.setPartition(QLatin1String("Ephemeral"));
        partitionQuery.setQuery(QLatin1String("[?_type=%type]"));
        partitionQuery.bindValue(QLatin1String("type"), QLatin1String("Partition"));
        mTestHelper->connection()->send(&partitionQuery);
        if (!mTestHelper->waitForResponse(&partitionQuery)) {
            QWARN("retrieving partition defs failed");
            return QList<QJsonObject>();
        }

        return partitionQuery.takeResults();
    }

    QtJsonDb::QJsonDbWatcher mWatcher;

private:
    void renameFiles(bool restoring)
    {
        const QString refFile = restoring ? QStringLiteral("partitions.json.bak") : QStringLiteral("partitions.json");
        QFileInfoList fileInfos1 = QFileInfo(QFINDTESTDATA(refFile)).absoluteDir().entryInfoList(
                    QStringList() << (restoring ? QStringLiteral("partitions*.json.bak") : QStringLiteral("partitions*json")),
                    QDir::Files | QDir::Readable);
        foreach (const QFileInfo &fileInfo1, fileInfos1) {
            const QString fileName1 = fileInfo1.absoluteFilePath();
            const QString fileName2 = restoring
                    ? fileName1.left(fileName1.lastIndexOf(QStringLiteral(".bak")))
                    : QString("%1.bak").arg(fileName1);
            if (!QFile::rename(fileName1, fileName2))
                QFAIL(qPrintable(QString("failed to rename %1 to %2 (restoring = %3)").arg(fileName1).arg(fileName2).arg(restoring)));
        }
    }

    TestHelper *mTestHelper;
};


void TestQJsonDbRequest::defaultPartition()
{
    defaultPartition_helper helper(this);

    int index = 0; // to avoid duplicate partition names

    // *** Case 1: two partitions, neither of which is marked as default or removable
    // *** Expected result: exactly one of the partitions gets set as default
    {
        QJsonArray defs;

        QJsonObject def1;
        def1.insert(QLatin1String("name"), QString("com.qt-project.test1_%1").arg(++index));
        def1.insert(QLatin1String("path"), QLatin1String("."));
        defs.append(def1);

        QJsonObject def2;
        def2.insert(QLatin1String("name"), QString("com.qt-project.test2_%1").arg(index));
        def2.insert(QLatin1String("path"), QLatin1String("."));
        defs.append(def2);

        QList<QJsonObject> results = helper.loadAndQueryPartitionDefs(defs);
        QCOMPARE(results.count(), 2);

        int defaultCount = 0;
        foreach (const QJsonObject &object, results)
            defaultCount += (object.value(QLatin1String("default")).toBool() ? 1 : 0);
        QCOMPARE(defaultCount, 1);
    }

    // *** Case 2: two non-removable partitions, exactly one of which is marked as default
    // *** Expected result: the original default partition is still the only one set as default
    {
        QJsonArray defs;

        QJsonObject def1;
        def1.insert(QLatin1String("name"), QString("com.qt-project.test1_%1").arg(++index));
        def1.insert(QLatin1String("path"), QLatin1String("."));
        defs.append(def1);

        QJsonObject def2;
        const QString expectedDefaultName = QString("com.qt-project.test2_%1").arg(index);
        def2.insert(QLatin1String("name"), expectedDefaultName);
        def2.insert(QLatin1String("path"), QLatin1String("."));
        def2.insert(QLatin1String("default"), true);
        defs.append(def2);

        QList<QJsonObject> results = helper.loadAndQueryPartitionDefs(defs);
        QCOMPARE(results.count(), 2);

        int defaultCount = 0;
        foreach (const QJsonObject &object, results) {
            if (object.value(QLatin1String("default")).toBool()) {
                QCOMPARE(object.value(QLatin1String("removable")).toBool(), false);
                QCOMPARE(object.value(QLatin1String("name")).toString(), expectedDefaultName);
                defaultCount++;
            }
        }
        QCOMPARE(defaultCount, 1);
    }

    // *** Case 3: exactly one non-removable partition, no default ones
    // *** Expected result: the non-removable partition is automatically set as default
    {
        QJsonArray defs;

        QJsonObject def1;
        def1.insert(QLatin1String("name"), QString("com.qt-project.test1_%1").arg(++index));
        def1.insert(QLatin1String("path"), QLatin1String("."));
        def1.insert(QLatin1String("removable"), true);
        defs.append(def1);

        QJsonObject def2;
        const QString expectedDefaultName = QString("com.qt-project.test2_%1").arg(index);
        def2.insert(QLatin1String("name"), expectedDefaultName);
        def2.insert(QLatin1String("path"), QLatin1String("."));
        // def2.insert(QLatin1String("removable"), false); // false by default
        defs.append(def2);

        QJsonObject def3;
        def3.insert(QLatin1String("name"), QString("com.qt-project.test3_%1").arg(index));
        def3.insert(QLatin1String("path"), QLatin1String("."));
        def3.insert(QLatin1String("removable"), true);
        defs.append(def3);

        QList<QJsonObject> results = helper.loadAndQueryPartitionDefs(defs);
        QCOMPARE(results.count(), 3);

        int defaultCount = 0;
        foreach (const QJsonObject &object, results) {
            if (object.value(QLatin1String("default")).toBool()) {
                QCOMPARE(object.value(QLatin1String("removable")).toBool(), false);
                QCOMPARE(object.value(QLatin1String("name")).toString(), expectedDefaultName);
                defaultCount++;
            }
        }
        QCOMPARE(defaultCount, 1);
    }

    // *** Case 4: only removable partitions
    // *** Expected response: an extra partition is created (in CWD) to act as the default one
    {
        QJsonArray defs;

        QJsonObject def1;
        def1.insert(QLatin1String("name"), QString("com.qt-project.test1_%1").arg(++index));
        def1.insert(QLatin1String("path"), QLatin1String("."));
        def1.insert(QLatin1String("removable"), true);
        defs.append(def1);

        QJsonObject def2;
        const QString expectedDefaultName = QString("com.qt-project.test2_%1").arg(index);
        def2.insert(QLatin1String("name"), expectedDefaultName);
        def2.insert(QLatin1String("path"), QLatin1String("."));
        def2.insert(QLatin1String("removable"), true);
        defs.append(def2);

        QList<QJsonObject> results = helper.loadAndQueryPartitionDefs(defs);
        QCOMPARE(results.count(), 3); // expect an extra partition

        int defaultCount = 0;
        foreach (const QJsonObject &object, results) {
            if (object.value(QLatin1String("default")).toBool()) {
                QCOMPARE(object.value(QLatin1String("removable")).toBool(), false);
                defaultCount++;
            }
        }
        QCOMPARE(defaultCount, 1);
    }
}

QTEST_MAIN(TestQJsonDbRequest)

#include "testqjsondbrequest.moc"