summaryrefslogtreecommitdiffstats
path: root/tests/auto/qkeyvaluestore/tst_qkeyvaluestore.cpp
blob: 6f95ebea7772c6a0a4bea4bf6499a21f7bd70f7b (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
/****************************************************************************
**
** 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 <QtCore/QString>
#include <QtTest/QtTest>

#include <QFile>
#include <QString>
#include <QByteArray>
#include <QHash>
#include <unistd.h>
#include <string.h>

#include "qkeyvaluestore.h"
#include "qkeyvaluestoretxn.h"
#include "qkeyvaluestorecursor.h"
#include "qkeyvaluestorefile.h"
#include "qkeyvaluestoreentry.h"

char testString[] = "this is a test";
quint32 testStringSize = 14;

class QKeyValueStoreTest : public QObject
{
    Q_OBJECT
    QString m_dbName;
    QString m_journal;
    QString m_tree;
    QString m_treeCopy;

public:
    QKeyValueStoreTest();
    void removeTemporaryFiles();
private Q_SLOTS:
    void sanityCheck();
    void storeAndLoad();
    void transactionLifetime();
    void autoSync();
    void manualSync();
    void compactionAfterRemove();
    void compactionAfterPut();
    void compactionAutoTrigger();
    void compactionContinuation();
    void fastOpen();
    void testNonAsciiChars();
    void buildBTreeFromScratch();
    void buildBTreeFromKnownState();
    void cursorSanityCheck();
    void cursorAscendingOrder();
    void cursorDescendingOrder();
    void cursorSeek();
    void cursorSeekRange();
    void fileSanityCheck();
    void fileWrite();
    void fileRead();
    void fileOffset();
    void fileSync();
    void fileTruncate();
    void fileStoreAndLoad();
#if 0
#endif
};

QKeyValueStoreTest::QKeyValueStoreTest()
{
    m_dbName = "db";
    m_journal = m_dbName + ".dat";
    m_tree = m_dbName + ".btr";
    m_treeCopy = m_dbName + ".old";
}

void QKeyValueStoreTest::removeTemporaryFiles()
{
    QFile::remove(m_journal);
    QFile::remove(m_tree);
    QFile::remove(m_treeCopy);
}

/*
 * In a way this is a useless test, however it fulfills a purpose.
 * All this operations should succeed unless something is really wrong.
 * So despite not testing the functionality, we test that the API returns
 * the right values.
 */
void QKeyValueStoreTest::sanityCheck()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());

    QKeyValueStoreTxn *readTxn = storage.beginRead();
    QVERIFY2(readTxn, "Read txn is NULL");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    QVERIFY2(writeTxn, "Write txn is NULL");

    delete readTxn;
    delete writeTxn;

    QVERIFY(storage.close());
    removeTemporaryFiles();
}

/*
 * Simple test. We store some values, then read the values back.
 */
void QKeyValueStoreTest::storeAndLoad()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());

    // Set the sync threshold very low
    storage.setSyncThreshold(5);

    QByteArray key("key");
    QByteArray value("value");

    // Create a write transaction
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    QVERIFY2(writeTxn, "Write txn is NULL");
    QVERIFY(writeTxn->put(key, value));
    QVERIFY(writeTxn->commit(100));

    // Create a read transaction
    QKeyValueStoreTxn *readTxn = storage.beginRead();
    QVERIFY2(readTxn, "Read txn is NULL");
    QByteArray retrievedValue;
    QVERIFY(readTxn->get(key, &retrievedValue));
    QCOMPARE(value, retrievedValue);
    delete readTxn;

    QVERIFY(storage.close());
    removeTemporaryFiles();
}

/*
 * We create a write transaction and store some values into the db.
 * Afterwards we create two transactions, one read and one write and
 * start writing on the db. The read transaction shouldn't see the changes.
 * After commiting the changes we create a new read transaction and see the
 * new values.
 */
void QKeyValueStoreTest::transactionLifetime()
{
    QByteArray key0("key0"), value0("value0");
    QByteArray key1("key1"), value1("value1");
    QByteArray key2("key2"), value2("value2");
    QByteArray key3("key3"), value3("value3");

    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());

    // Set the sync threshold very low
    storage.setSyncThreshold(5);

    // Create a write transaction
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    QVERIFY2(writeTxn, "Write txn is NULL");
    QVERIFY(writeTxn->put(key0, value0));
    QVERIFY(writeTxn->commit(100));
#if defined(JSONDB_USE_KVS_MULTIPLE_TRANSACTIONS)
    // Now, the transaction is commited. Let's create the other two.
    QKeyValueStoreTxn *readTxn = storage.beginRead();
    QVERIFY2(readTxn, "Read txn is NULL");
    QKeyValueStoreTxn *newWriteTxn = storage.beginWrite();
    QVERIFY2(newWriteTxn, "newWrite txn is NULL");

    // Write some more entries
    QVERIFY(newWriteTxn->put(key1, value1));
    QVERIFY(newWriteTxn->put(key2, value2));
    QVERIFY(newWriteTxn->put(key3, value3));

    // Try to read those entries
    QByteArray recoveredValue;
    QVERIFY(readTxn->get(key0, &recoveredValue));
    QCOMPARE(recoveredValue, value0);
    QVERIFY(!readTxn->get(key1, &recoveredValue));
    QVERIFY(!readTxn->get(key2, &recoveredValue));
    QVERIFY(!readTxn->get(key3, &recoveredValue));

    // However the write transaction can see it
    QVERIFY(newWriteTxn->get(key1, &recoveredValue));
    QCOMPARE(value1, recoveredValue);

    // Commit the writes
    QVERIFY(newWriteTxn->commit(101));

    // Try to get them, once more
    QVERIFY(!readTxn->get(key1, &recoveredValue));
    QVERIFY(!readTxn->get(key2, &recoveredValue));
    QVERIFY(!readTxn->get(key3, &recoveredValue));

    // Create a new read transaction and get them
    QKeyValueStoreTxn *newReadTxn = storage.beginRead();
    QByteArray recoveredValue1, recoveredValue2, recoveredValue3;
    // Try to get them, once more
    QVERIFY(newReadTxn->get(key1, &recoveredValue1));
    QCOMPARE(value1, recoveredValue1);
    QVERIFY(newReadTxn->get(key2, &recoveredValue2));
    QCOMPARE(value2, recoveredValue2);
    QVERIFY(newReadTxn->get(key3, &recoveredValue3));
    QCOMPARE(value3, recoveredValue3);
#endif
    QVERIFY(storage.close());
    removeTemporaryFiles();
}

/*
 * It seems that QMap and QByteArray do not share its love for non-ascii
 * characters. This test case checks that.
 */
void QKeyValueStoreTest::testNonAsciiChars()
{
    removeTemporaryFiles();

    char rawKey0[] = { 0, 0, 0, 2, 0 };
    char rawKey1[] = { 0, 0, 0, 2, 1 };
    char rawKey2[] = { 0, 0, 0, 2, 2 };
    char rawKey3[] = { 0, 0, 0, 2, 3 };
    int rawKeySize = 5;
    QByteArray key0(rawKey0, rawKeySize);
    QByteArray key1(rawKey1, rawKeySize);
    QByteArray key2(rawKey2, rawKeySize);
    QByteArray key3(rawKey3, rawKeySize);
    char rawValue0[] = { 1, 0, 0, 2, 0 };
    char rawValue1[] = { 1, 0, 0, 2, 1 };
    char rawValue2[] = { 1, 0, 0, 2, 2 };
    char rawValue3[] = { 1, 0, 0, 2, 3 };
    int rawValueSize = 5;
    QByteArray value0(rawValue0, rawValueSize);
    QByteArray value1(rawValue1, rawValueSize);
    QByteArray value2(rawValue2, rawValueSize);
    QByteArray value3(rawValue3, rawValueSize);

    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    // Set the sync threshold very low
    storage.setSyncThreshold(5);

    // Create a write transaction
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    QVERIFY2(writeTxn, "Write txn is NULL");
    QVERIFY(writeTxn->put(key0, value0));
    QVERIFY(writeTxn->put(key1, value1));
    QVERIFY(writeTxn->put(key2, value2));
    QVERIFY(writeTxn->put(key3, value3));
    QVERIFY(writeTxn->commit(100));

    QKeyValueStoreTxn *readTxn = storage.beginRead();
    QVERIFY2(readTxn, "Read txn is NULL");
    QByteArray recoveredValue;
    QVERIFY(readTxn->get(key0, &recoveredValue));
    QCOMPARE(recoveredValue, value0);
    QVERIFY(readTxn->get(key1, &recoveredValue));
    QCOMPARE(recoveredValue, value1);
    QVERIFY(readTxn->get(key2, &recoveredValue));
    QCOMPARE(recoveredValue, value2);
    QVERIFY(readTxn->get(key3, &recoveredValue));
    QCOMPARE(recoveredValue, value3);
    QVERIFY(readTxn->abort());

    removeTemporaryFiles();
}

/*
 * We create a database and start writing elements to it.
 * We count the number of marks on the DB and check the status
 * of the btree.
 */
void QKeyValueStoreTest::autoSync()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    /*
     * We write 100 entries, and check if the automatic sync kicked in.
     * This can be verified by checking the number of marks on the db file.
     * Entries 0..9 weight 20 bytes, and the rest 21. That's about 2090
     * bytes, therefore we should have 2 marks (2nd mark comes at 2048 bytes).
     */
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i + 1024));
    }
    QVERIFY(storage.close());
    // Now we open the file and inspect it.
    QFile db(m_journal);
    db.open(QIODevice::ReadOnly);
    QVERIFY(db.size() != 0);
    QDataStream stream(&db);
    stream.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream >> count;
    while (!stream.atEnd()) {
        QByteArray key;
        stream >> key;
        quint8 operation = 0;
        stream >> operation;
        quint32 offsetToStart = 0;
        stream >> offsetToStart;
        QByteArray value;
        stream >> value;
        quint32 hash = 0xFFFFFFFF;
        stream >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream >> tag;
            quint32 marker = 0;
            stream >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream >> dataTimestamp;
                stream >> hash;
                numberOfMarkers++;
                stream >> count;
            } else {
                count = marker;
            }
            found = 0;
        }
    }
    // 2 automatic markers and one after calling close
    QCOMPARE(numberOfMarkers, 3);
    // And now to inspect the btree
    QFile tree(m_tree);
    tree.open(QIODevice::ReadOnly);
    QDataStream treeStream(&tree);
    treeStream.setByteOrder(QDataStream::LittleEndian);
    quint64 treeTimestamp = 0;
    found = 0;
    treeStream >> count;
    QCOMPARE(count, (quint32)100);
    while (!treeStream.atEnd()) {
        QByteArray key;
        qint64 value;
        treeStream >> key;
        treeStream >> value;
        found++;
        if (count == found)
            break;
    }
    treeStream >> treeTimestamp;
    quint32 hash = 0xFFFFFFFF;
    treeStream >> hash;
    quint32 computedHash = qHash(treeTimestamp);
    QCOMPARE(hash, computedHash);
    QCOMPARE(treeTimestamp, dataTimestamp);

    removeTemporaryFiles();
}

/*
 * We create a database and start writing elements to it.
 * We count the number of marks on the DB and check the status
 * of the btree.
 */
void QKeyValueStoreTest::manualSync()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    // Set it on manual sync mode
    storage.setSyncThreshold(0);
    // Now run the test
    QVERIFY(storage.open());
    /*
     * We write 100 entries, and check if the automatic sync kicked in.
     * This can be verified by checking the number of marks on the db file.
     * Entries 0..9 weight 20 bytes, and the rest 21. That's about 2090
     * bytes. Since this is in manual sync mode, we should have no markers until
     * we call close or sync.
     */
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(100));
    }
    QVERIFY(storage.close());
    // Now we open the file and inspect it.
    QFile db(m_journal);
    db.open(QIODevice::ReadOnly);
    QDataStream stream(&db);
    stream.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream >> count;
    while (!stream.atEnd()) {
        QByteArray key;
        stream >> key;
        quint8 operation = 0;
        stream >> operation;
        quint32 offsetToStart = 0;
        stream >> offsetToStart;
        QByteArray value;
        stream >> value;
        quint32 hash = 0xFFFFFFFF;
        stream >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream >> tag;
            quint32 marker = 0;
            stream >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream >> dataTimestamp;
                stream >> hash;
                numberOfMarkers++;
                stream >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    // One marker after calling close
    QCOMPARE(numberOfMarkers, 1);
    // And now to inspect the btree
    QFile tree(m_tree);
    tree.open(QIODevice::ReadOnly);
    QDataStream treeStream(&tree);
    treeStream.setByteOrder(QDataStream::LittleEndian);
    quint64 treeTimestamp = 0;
    found = 0;
    treeStream >> count;
    QCOMPARE(count, (quint32)100);
    while (!treeStream.atEnd()) {
        QByteArray key;
        qint64 value;
        treeStream >> key;
        treeStream >> value;
        found++;
        if (count == found)
            break;
    }
    treeStream >> treeTimestamp;
    quint32 hash = 0xFFFFFFFF;
    treeStream >> hash;
    quint32 computedHash = qHash(treeTimestamp);
    QCOMPARE(hash, computedHash);
    QCOMPARE(treeTimestamp, dataTimestamp);

    removeTemporaryFiles();
}

/*
 * To test compaction we need to add elements and then
 * remove some of them. The compacted file should not have those elements.
 */
void QKeyValueStoreTest::compactionAfterRemove()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    // Set it on manual sync mode
    storage.setSyncThreshold(0);
    // Now run the test
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i));
    }
    // Let's remove all of them but one
    for (int i = 0; i < 99; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->remove(key));
        QVERIFY(writeTxn->commit(i));
    }
    QVERIFY(storage.sync());
    // Check that all elements are there.
    qint32 addOperations = 0, removeOperations = 0;
    QFile check1(m_dbName + ".dat");
    QVERIFY(check1.open(QIODevice::ReadOnly));
    QDataStream stream1(&check1);
    stream1.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream1 >> count;
    while (!stream1.atEnd()) {
        QByteArray key;
        stream1 >> key;
        quint8 operation = 0;
        stream1 >> operation;
        // Add
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream1 >> offsetToStart;
        QByteArray value;
        stream1 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream1 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream1 >> tag;
            quint32 marker = 0;
            stream1 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream1 >> dataTimestamp;
                stream1 >> hash;
                numberOfMarkers++;
                stream1 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check1.close();
    QCOMPARE(addOperations, 100);
    QCOMPARE(removeOperations, 99);
    // Let's compact the file and check that only one element is there.
    QVERIFY(storage.compact());
    QFile check2(m_dbName + ".dat");
    QVERIFY(check2.open(QIODevice::ReadOnly));
    QDataStream stream2(&check2);
    stream2.setByteOrder(QDataStream::LittleEndian);
    addOperations = 0;
    removeOperations = 0;
    while (!stream2.atEnd()) {
        QByteArray key;
        stream2 >> key;
        quint8 operation = 0;
        stream2 >> operation;
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream2 >> offsetToStart;
        QByteArray value;
        stream2 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream2 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream2 >> tag;
            quint32 marker = 0;
            stream2 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream2 >> dataTimestamp;
                stream2 >> hash;
                numberOfMarkers++;
                stream2 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check2.close();
    QCOMPARE(addOperations, 1);
    QCOMPARE(removeOperations, 0);
    // Close the file
    QVERIFY(storage.close());
    removeTemporaryFiles();
}

/*
 * To test compaction we need to add elements and update them.
 * The compacted file should have only one version of each element.
 */
void QKeyValueStoreTest::compactionAfterPut()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    // Set it on manual sync mode
    storage.setSyncThreshold(0);
    // Now run the test
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QByteArray key("key-0");
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i));
    }
    QVERIFY(storage.sync());
    // Check that all elements are there.
    qint32 addOperations = 0, removeOperations = 0;
    QFile check1(m_dbName + ".dat");
    QVERIFY(check1.open(QIODevice::ReadOnly));
    QDataStream stream1(&check1);
    stream1.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream1 >> count;
    while (!stream1.atEnd()) {
        QByteArray key;
        stream1 >> key;
        quint8 operation = 0;
        stream1 >> operation;
        // Add
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream1 >> offsetToStart;
        QByteArray value;
        stream1 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream1 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream1 >> tag;
            quint32 marker = 0;
            stream1 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream1 >> dataTimestamp;
                stream1 >> hash;
                numberOfMarkers++;
                stream1 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check1.close();
    QCOMPARE(addOperations, 100);
    QCOMPARE(removeOperations, 0);
    // Let's compact the file and check that only one element is there.
    QVERIFY(storage.compact());
    QFile check2(m_dbName + ".dat");
    QVERIFY(check2.open(QIODevice::ReadOnly));
    QDataStream stream2(&check2);
    stream2.setByteOrder(QDataStream::LittleEndian);
    addOperations = 0;
    removeOperations = 0;
    while (!stream2.atEnd()) {
        QByteArray key;
        stream2 >> key;
        quint8 operation = 0;
        stream2 >> operation;
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream2 >> offsetToStart;
        QByteArray value;
        stream2 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream2 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream2 >> tag;
            quint32 marker = 0;
            stream2 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream2 >> dataTimestamp;
                stream2 >> hash;
                numberOfMarkers++;
                stream2 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check2.close();
    QCOMPARE(addOperations, 1);
    QCOMPARE(removeOperations, 0);
    // Close the file
    QVERIFY(storage.close());
    removeTemporaryFiles();
}

/*
 * To test this type of compaction we need to add elements until we trigger
 * a compaction round. There are two cases, after remove or after too many
 * updates.
 */
void QKeyValueStoreTest::compactionAutoTrigger()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    // Now run the test
    QVERIFY(storage.open());
    // Manual sync
    storage.setSyncThreshold(0);
    // Compact after 100 operations
    storage.setCompactThreshold(100);
    QByteArray value("012345678901234");
    QByteArray key("key-0");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i));
    }
    // After sync there should be only one element
    QVERIFY(storage.sync());
    qint32 addOperations = 0, removeOperations = 0;
    QFile check1(m_dbName + ".dat");
    QVERIFY(check1.open(QIODevice::ReadOnly));
    QDataStream stream1(&check1);
    stream1.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream1 >> count;
    while (!stream1.atEnd()) {
        QByteArray key;
        stream1 >> key;
        quint8 operation = 0;
        stream1 >> operation;
        // Add
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream1 >> offsetToStart;
        QByteArray value;
        stream1 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream1 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream1 >> tag;
            quint32 marker = 0;
            stream1 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream1 >> dataTimestamp;
                stream1 >> hash;
                numberOfMarkers++;
                stream1 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check1.close();
    // There should be only one element
    QCOMPARE(addOperations, 1);
    QCOMPARE(removeOperations, 0);

    removeTemporaryFiles();
}

/*
 * What we test here is if the file is usable after compaction.
 * First test is to write some more elements and then to close it
 * and open it.
 */
void QKeyValueStoreTest::compactionContinuation()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    // Manual sync
    storage.setSyncThreshold(0);
    // Compact after 100 operations
    storage.setCompactThreshold(100);
    // Now run the test
    QVERIFY(storage.open());
    {
        QByteArray value("012345678901234");
        QByteArray key("key-0");
        for (int i = 0; i < 100; i++) {
            QKeyValueStoreTxn *writeTxn = storage.beginWrite();
            QVERIFY2(writeTxn, "writeTxn is NULL");
            QVERIFY(writeTxn->put(key, value));
            QVERIFY(writeTxn->commit(i));
        }
    }
    // After sync there should be only one element
    QVERIFY(storage.sync());
    qint32 addOperations = 0, removeOperations = 0;
    QFile check1(m_dbName + ".dat");
    QVERIFY(check1.open(QIODevice::ReadOnly));
    QDataStream stream1(&check1);
    stream1.setByteOrder(QDataStream::LittleEndian);
    quint32 count = 0, found = 0;
    int numberOfMarkers = 0;
    quint32 m_marker = 0x55AAAA55;
    quint32 tag = 0;
    quint64 dataTimestamp = 0;
    stream1 >> count;
    while (!stream1.atEnd()) {
        QByteArray key;
        stream1 >> key;
        quint8 operation = 0;
        stream1 >> operation;
        // Add
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream1 >> offsetToStart;
        QByteArray value;
        stream1 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream1 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream1 >> tag;
            quint32 marker = 0;
            stream1 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream1 >> dataTimestamp;
                stream1 >> hash;
                numberOfMarkers++;
                stream1 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check1.close();
    // There should be only one element
    QCOMPARE(addOperations, 1);
    QCOMPARE(removeOperations, 0);
    QCOMPARE(storage.tag(), (quint32)99);
    // Now we add some more elements and see what happens
    {
        QByteArray value("012345678901234");
        QByteArray key("key-1");
        for (int i = 100; i < 200; i++) {
            QKeyValueStoreTxn *writeTxn = storage.beginWrite();
            QVERIFY2(writeTxn, "writeTxn is NULL");
            QVERIFY(writeTxn->put(key, value));
            QVERIFY(writeTxn->commit(i));
        }
    }
    QVERIFY(storage.sync());
    addOperations = 0;
    removeOperations = 0;
    QFile check2(m_dbName + ".dat");
    QVERIFY(check2.open(QIODevice::ReadOnly));
    QDataStream stream2(&check2);
    stream2.setByteOrder(QDataStream::LittleEndian);
    count = 0;
    found = 0;
    numberOfMarkers = 0;
    stream2 >> count;
    while (!stream2.atEnd()) {
        QByteArray key;
        stream2 >> key;
        quint8 operation = 0;
        stream2 >> operation;
        // Add
        if (operation == QKeyValueStoreEntry::Add)
            addOperations++;
        else
            removeOperations++;
        quint32 offsetToStart = 0;
        stream2 >> offsetToStart;
        QByteArray value;
        stream2 >> value;
        quint32 hash = 0xFFFFFFFF;
        stream2 >> hash;
        found++;
        if (count == found) {
            // Do we have a marker?
            stream2 >> tag;
            quint32 marker = 0;
            stream2 >> marker;
            if (marker == m_marker) {
                // Yes we do!
                stream2 >> dataTimestamp;
                stream2 >> hash;
                numberOfMarkers++;
                stream2 >> count;
            } else
                count = marker;
            found = 0;
        }
    }
    check2.close();
    // There should be only two elements
    QCOMPARE(addOperations, 2);
    QCOMPARE(removeOperations, 0);

    // Now close the file
    QVERIFY(storage.close());
    // And open it in a new element
    QKeyValueStore storage2(m_dbName);
    QVERIFY(storage2.open());
    QCOMPARE(storage2.tag(), (quint32)199);
    removeTemporaryFiles();
}

/*
 * We store values in the file.
 * We close it and then try to open it again.
 */
void QKeyValueStoreTest::fastOpen()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());

    // Disable the autosync
    storage.setSyncThreshold(0);

    QByteArray key1("key1");
    QByteArray value1("value1");

    // Create a write transaction
    QKeyValueStoreTxn *writeTxn1 = storage.beginWrite();
    QVERIFY2(writeTxn1, "Write txn1 is NULL");
    QVERIFY(writeTxn1->put(key1, value1));
    QVERIFY(writeTxn1->commit(100));
    QVERIFY(storage.sync());
    // At this point we have one marker.
    QByteArray key2("key2");
    QByteArray value2("value2");

    // Create a write transaction
    QKeyValueStoreTxn *writeTxn2 = storage.beginWrite();
    QVERIFY2(writeTxn2, "Write txn2 is NULL");
    QVERIFY(writeTxn2->put(key2, value2));
    QVERIFY(writeTxn2->commit(200));
    // Now we have two markers, so we close the storage.
    QVERIFY(storage.close());

    /*
     * We open the storage and count the markers. There should be two of them,
     * however since this will be a fast open, we will only find the last one.
     * That means there will be only one marker.
     */
    QKeyValueStore storage2(m_dbName);
    QVERIFY(storage2.open());
    // Now we count the markers
    QCOMPARE(storage2.markers(), 1);

    // Done, let's go.
    QVERIFY(storage2.close());
    removeTemporaryFiles();
}

/*
 * We write entries to the database and then close it.
 * We delete the btree file and open the database again.
 * The algorithm should rebuild the btree from the journal.
 */
void QKeyValueStoreTest::buildBTreeFromScratch()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i));
    }
    // Now we close the file
    QVERIFY(storage.close());
    // Remove the file
    QFile::remove(m_tree);
    // Now create a new storage and see if it builds the tree.
    QKeyValueStore storage2(m_dbName);
    QVERIFY(storage2.open());
    QKeyValueStoreTxn *readTxn = storage2.beginRead();
    QVERIFY2(readTxn, "readTxn is NULL");
    QByteArray getKey("key-89");
    QByteArray getValue;
    QVERIFY(readTxn->get(getKey, &getValue));
    QCOMPARE(getValue, value);
    storage2.close();

    removeTemporaryFiles();
}

/*
 * We write entries to the database and then close it.
 * We copy the btree file and then add some more entries to the db.
 * We replace the new btree file with the old one and open the database again.
 * The algorithm should rebuild the btree from the journal.
 */
void QKeyValueStoreTest::buildBTreeFromKnownState()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    for (int i = 0; i < 100; i++) {
        QKeyValueStoreTxn *writeTxn = storage.beginWrite();
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
        QVERIFY(writeTxn->commit(i));
    }
    // At this time we only have two markers.
    QFile::copy(m_tree, m_treeCopy);
    // Now we close the file
    QVERIFY(storage.close());
    // Remove the file
    QFile::remove(m_tree);
    QFile::rename(m_treeCopy, m_tree);

    // Now create a new storage and see if it builds the tree.
    QKeyValueStore storage2(m_dbName);
    QVERIFY(storage2.open());
    QKeyValueStoreTxn *readTxn = storage2.beginRead();
    QVERIFY2(readTxn, "readTxn is NULL");
    QByteArray getKey("key-89");
    QByteArray getValue;
    QVERIFY(readTxn->get(getKey, &getValue));
    QCOMPARE(getValue, value);
    QVERIFY(storage2.close());
    removeTemporaryFiles();
}

/*
 * This is a very useless test, but everything here should work.
 */
void QKeyValueStoreTest::cursorSanityCheck()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    for (int i = 0; i < 100; i++) {
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
    }
    // Now we have 100 items, let's use the cursor and iterate over the first and the last.
    QKeyValueStoreCursor *cursor = new QKeyValueStoreCursor(writeTxn);
    // At this point the cursor should be pointing to the first item
    QVERIFY(cursor->first());
    QByteArray firstElementKey("key-0");
    QByteArray lastElementKey("key-99");
    QByteArray recoveredKey;
    QByteArray recoveredValue;
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, firstElementKey);
    QCOMPARE(recoveredValue, value);
    // Move to the last element
    QVERIFY(cursor->last());
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, lastElementKey);
    QCOMPARE(recoveredValue, value);
    removeTemporaryFiles();
}

/*
 * This is a funny test, ascending order means ascending in a string kind of way.
 * Therefore the keys are ordered as follows:
 * key-0
 * key-1
 * key-10
 * key-11
 * ...
 * key-2
 * key-20
 * ...
 * key-98
 * key-99
 */
void QKeyValueStoreTest::cursorAscendingOrder()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    bool test = false;
    test = storage.open();
    QCOMPARE(test, true);
    QByteArray value("012345678901234");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    for (int i = 0; i < 100; i++) {
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        test = writeTxn->put(key, value);
        QCOMPARE(test, true);
    }
    // Now we have 100 items, let's use the cursor and iterate over them
    QKeyValueStoreCursor *cursor = new QKeyValueStoreCursor(writeTxn);
    QVERIFY(cursor->first());
    // At this point the cursor should be pointing to the first item
    for (int i = 0; i < 10; i++) {
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QByteArray recoveredKey;
        QByteArray recoveredValue;
        QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
        QCOMPARE(recoveredKey, key);
        QCOMPARE(recoveredValue, value);
        QVERIFY(cursor->next());
        if (0 == i)
            continue;
        for (int j = 0; j < 10; j++, cursor->next()) {
            QString baseKey2(baseKey);
            QString number2;
            number2.setNum(j);
            baseKey2.append(number2);
            key = baseKey2.toAscii();
            QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
            QCOMPARE(recoveredKey, key);
            QCOMPARE(recoveredValue, value);
        }
    }
    removeTemporaryFiles();
}

/*
 * This is a funny test, descending order means ascending in a string kind of way.
 * Therefore the keys are ordered as follows:
 * key-99
 * key-98
 * ...
 * key-20
 * key-2
 * ...
 * key-11
 * key-10
 * key-1
 * key-0
 */
void QKeyValueStoreTest::cursorDescendingOrder()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    for (int i = 0; i < 100; i++) {
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
    }
    // Now we have 100 items, let's use the cursor and iterate over them
    QKeyValueStoreCursor *cursor = new QKeyValueStoreCursor(writeTxn);
    QVERIFY(cursor->last());
    // At this point the cursor should be pointing to the last item
    QByteArray recoveredKey;
    QByteArray recoveredValue;
    QByteArray key;
    for (int i = 9; i > 0; i--) {
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        for (int j = 9; j >= 0; j--, cursor->previous()) {
            QString baseKey2(baseKey);
            QString number2;
            number2.setNum(j);
            baseKey2.append(number2);
            key = baseKey2.toAscii();
            QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
            QCOMPARE(recoveredKey, key);
            QCOMPARE(recoveredValue, value);
        }
        QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
        key = baseKey.toAscii();
        QCOMPARE(recoveredKey, key);
        QCOMPARE(recoveredValue, value);
        QVERIFY(cursor->previous());
    }
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    key = "key-0";
    QCOMPARE(recoveredKey, key);
    QCOMPARE(recoveredValue, value);
    removeTemporaryFiles();
}

void QKeyValueStoreTest::cursorSeek()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    for (int i = 0; i < 100; i++) {
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        number.setNum(i);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
    }
    // Now we have 100 items, let's use the cursor and iterate over them.
    QKeyValueStoreCursor *cursor = new QKeyValueStoreCursor(writeTxn);
    // At this point the cursor should be pointing to the first item
    // First let's try seeking a known element
    QByteArray key55("key-55");
    QByteArray recoveredKey;
    QByteArray recoveredValue;
    QVERIFY(cursor->seek(key55));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key55);
    QCOMPARE(recoveredValue, value);
    // Now let's try an unknown element
    QByteArray key101("key-101");
    QVERIFY2(!cursor->seek(key101), "We have an unknown element on the array (101)");
    // And let's finish with a new known element
    QByteArray key10("key-10");
    QVERIFY(cursor->seek(key10));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key10);
    QCOMPARE(recoveredValue, value);
    // Done
    removeTemporaryFiles();
}

/*
 * seek and seekRange are similar. The difference is on the "not found"
 * reply. While seeks returns false, seekRange might return an element.
 */
void QKeyValueStoreTest::cursorSeekRange()
{
    removeTemporaryFiles();
    QKeyValueStore storage(m_dbName);
    QVERIFY(storage.open());
    QByteArray value("012345678901234");
    QKeyValueStoreTxn *writeTxn = storage.beginWrite();
    for (int i = 1; i < 100; i++) {
        QVERIFY2(writeTxn, "writeTxn is NULL");
        QString number;
        // Only even numbers
        number.setNum(i * 2);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QVERIFY(writeTxn->put(key, value));
    }
    // Now we have 100 items, let's use the cursor and iterate over them.
    // We do this first using the default EqualOrGreater policy.
    QKeyValueStoreCursor *cursor = new QKeyValueStoreCursor(writeTxn);
    QVERIFY(cursor->first());
    // At this point the cursor should be pointing to the first item
    // First let's try seeking a known element
    QByteArray key54("key-54");
    QByteArray recoveredKey;
    QByteArray recoveredValue;
    QVERIFY(cursor->seekRange(key54));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key54);
    QCOMPARE(recoveredValue, value);
    // Now let's try an unknown element
    QByteArray key999("key-999");
    QVERIFY2(!cursor->seekRange(key999), "We have an unknown element on the array (999)");
    // Now let's try an element that does not exist but that will return a
    // greater element
    QByteArray key41("key-41");
    QByteArray key42("key-42");
    QVERIFY(cursor->seekRange(key41));
    // It should return 42
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key42);
    QCOMPARE(recoveredValue, value);
    // And let's finish with a new known element
    QByteArray key10("key-10");
    QVERIFY(cursor->seekRange(key10));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key10);
    QCOMPARE(recoveredValue, value);
    // Now we try elements that are not found but have a greater than
    QByteArray key101("key-101");
    QByteArray key101greater("key-102");
    QVERIFY(cursor->seekRange(key101));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key101greater);
    QCOMPARE(recoveredValue, value);
    // Now, let's try the EqualOrLess policy.
    QByteArray key52("key-52");
    QVERIFY(cursor->seekRange(key52, QKeyValueStoreCursor::EqualOrLess));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key52);
    QCOMPARE(recoveredValue, value);
    QByteArray key50("key-50");
    QByteArray key51("key-51");
    QVERIFY(cursor->seekRange(key51, QKeyValueStoreCursor::EqualOrLess));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key50);
    QCOMPARE(recoveredValue, value);
    // Try an element smaller than the first element
    QByteArray key1("key-1");
    QVERIFY2(!cursor->seekRange(key1, QKeyValueStoreCursor::EqualOrLess), "We have an unknown element on the array (1)");
    // Try an element larger than the first but smaller than the second, we
    // should get the first element.
    QByteArray key2Space("key-2 ");
    QByteArray key2("key-2");
    QVERIFY(cursor->seekRange(key2Space, QKeyValueStoreCursor::EqualOrLess));
    QVERIFY(cursor->current(&recoveredKey, &recoveredValue));
    QCOMPARE(recoveredKey, key2);
    QCOMPARE(recoveredValue, value);
    // Finally we will try a simple loop
    // EqualOrGreater first
    int index = 0;
    int elements = 0;
    QByteArray key90("key-90");
    for (index = 90, cursor->seekRange(key90);
         cursor->current(&recoveredKey, &recoveredValue);
         cursor->next(), index+=2) {
        QString number;
        // Only even numbers
        number.setNum(index);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QCOMPARE(key, recoveredKey);
        elements++;
    }
    QCOMPARE(elements, 5);
    elements = 0;
    QByteArray key99("key-99");
    for (index = 99, cursor->seekRange(key99);
         cursor->current(&recoveredKey, &recoveredValue);
         cursor->next(), index+=2) {
        QString number;
        // Only even numbers
        number.setNum(index);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QCOMPARE(key, recoveredKey);
        elements++;
    }
    // EqualOrLess now
    for (index = 10, cursor->seekRange(key10, QKeyValueStoreCursor::EqualOrLess);
         cursor->current(&recoveredKey, &recoveredValue);
         cursor->previous(), index-=2) {
        QString number;
        // Only even numbers
        number.setNum(index);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QCOMPARE(key, recoveredKey);
        elements++;
    }
    QCOMPARE(elements, 1);
    elements = 0;
    for (index = 1, cursor->seekRange(key1, QKeyValueStoreCursor::EqualOrLess);
         cursor->current(&recoveredKey, &recoveredValue);
         cursor->previous(), index-=2) {
        QString number;
        // Only even numbers
        number.setNum(index);
        QString baseKey("key-");
        baseKey.append(number);
        QByteArray key = baseKey.toAscii();
        QCOMPARE(key, recoveredKey);
        elements++;
    }
    QCOMPARE(elements, 0);

    // Done
    removeTemporaryFiles();
}

/*
 * As all the other sanity checks this is pretty useless, although it
 * checks that the API returns the correct values.
 */
void QKeyValueStoreTest::fileSanityCheck()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QVERIFY(file.close());
    removeTemporaryFiles();
}

/*
 * Create a file and write something to it, then check the file size.
 */
void QKeyValueStoreTest::fileWrite()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    QVERIFY(file.close());
    removeTemporaryFiles();
}

/*
 * Create a file and write something to it, then check the file size.
 * Once that is done, read the content back and check it is the same.
 */
void QKeyValueStoreTest::fileRead()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    // Now read the content back
    char buffer[15];
    file.setOffset(0);
    QCOMPARE(file.read(buffer, testStringSize), (qint32)testStringSize);
    QCOMPARE(strncmp(buffer, testString, testStringSize), 0);
    QVERIFY(file.close());
    removeTemporaryFiles();
}

/*
 * Create a file and write some data into it. Store the offset and then
 * write some more data into it. Read the new data using the stored offset.
 * Check the total file size.
 */
void QKeyValueStoreTest::fileOffset()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    qint64 offset = file.size();
    // Write some more data into the file
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)(2*testStringSize));
    // Now read the data from the stored offset.
    char buffer[15];
    file.setOffset(offset);
    QCOMPARE(file.read(buffer, testStringSize), (qint32)testStringSize);
    QCOMPARE(strncmp(buffer, testString, testStringSize), 0);
    offset = file.size();
    // Write some more data into the file
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)(3*testStringSize));
    // Now read the data from the stored offset.
    file.setOffset(offset);
    QCOMPARE(file.read(buffer, testStringSize), (qint32)testStringSize);
    QCOMPARE(strncmp(buffer, testString, testStringSize), 0);
    QVERIFY(file.close());
    removeTemporaryFiles();
}

/*
 * Create a new file and write some data to it. Without closing the file,
 * open a new instance of it and start reading it. It might or not return the
 * contents. On the first file call sync. Now read on the second file, the content
 * should be visible.
 */
void QKeyValueStoreTest::fileSync()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QKeyValueStoreFile file2("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    // Open the file a second time and try to read from it.
    QVERIFY(file2.open());
    char buffer[15];
    file.setOffset(0);
    QCOMPARE(file2.read(buffer, testStringSize), (qint32)testStringSize);
    QCOMPARE(file2.size(), (qint64)testStringSize);
    QVERIFY(file2.close());
    // Now sync the file
    file.sync();
    // Open the other file and check the content
    QVERIFY(file2.open());
    QCOMPARE(file2.size(), (qint64)testStringSize);
    QVERIFY(file2.close());
    QVERIFY(file.close());
    removeTemporaryFiles();
}

/*
 * Create a new file and write some data to it checking the file size.
 * Open the file again with the truncate flag on and check the file size.
 */
void QKeyValueStoreTest::fileTruncate()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    QVERIFY(file.close());
    QKeyValueStoreFile file2("db.dat", true);
    QVERIFY(file2.open());
    QCOMPARE(file2.size(), (qint64)0);
    QVERIFY(file2.close());
    removeTemporaryFiles();
}

/*
 * Create a file, write some data into it and then read it.
 */
void QKeyValueStoreTest::fileStoreAndLoad()
{
    removeTemporaryFiles();
    QKeyValueStoreFile file("db.dat");
    QVERIFY(file.open());
    QCOMPARE(file.size(), (qint64)0);
    // Write something to the file.
    QCOMPARE(file.write(testString, testStringSize), (qint32)testStringSize);
    QCOMPARE(file.size(), (qint64)testStringSize);
    // Now read it back
    char buffer[15];
    QCOMPARE(file.read(buffer, testStringSize), (qint32)testStringSize);
    QByteArray written(testString, testStringSize);
    QByteArray got(buffer, testStringSize);
    QCOMPARE(written, got);
    // Done
    QVERIFY(file.close());
    removeTemporaryFiles();
}

#if 0
#endif
QTEST_APPLESS_MAIN(QKeyValueStoreTest)

#include "tst_qkeyvaluestore.moc"