summaryrefslogtreecommitdiffstats
path: root/tests/maildirresourcetest.cpp
blob: 968abde6e6e3ea3659811ebac9a086b2a21d991a (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
#include <QtTest>

#include <QString>
#include <KMime/Message>

#include "maildirresource/maildirresource.h"
#include "store.h"
#include "resourcecontrol.h"
#include "commands.h"
#include "entitybuffer.h"
#include "resourceconfig.h"
#include "modelresult.h"
#include "pipeline.h"
#include "log.h"
#include "test.h"

#define ASYNCCOMPARE(actual, expected) \
do {\
    if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
        return KAsync::error<void>(1, "Comparison failed.");\
} while (0)

#define ASYNCVERIFY(statement) \
do {\
    if (!QTest::qVerify((statement), #statement, "", __FILE__, __LINE__))\
        return KAsync::error<void>(1, "Verify failed.");\
} while (0)

using namespace Sink;

static bool copyRecursively(const QString &srcFilePath, const QString &tgtFilePath)
{
    QFileInfo srcFileInfo(srcFilePath);
    if (srcFileInfo.isDir()) {
        QDir targetDir(tgtFilePath);
        targetDir.cdUp();
        if (!targetDir.mkdir(QFileInfo(srcFilePath).fileName())) {
            qWarning() << "Failed to create directory " << tgtFilePath;
            return false;
        }
        QDir sourceDir(srcFilePath);
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot | QDir::Hidden | QDir::System);
        foreach (const QString &fileName, fileNames) {
            const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName;
            const QString newTgtFilePath = tgtFilePath + QLatin1Char('/') + fileName;
            if (!copyRecursively(newSrcFilePath, newTgtFilePath))
                return false;
        }
    } else {
        if (!QFile::copy(srcFilePath, tgtFilePath)) {
            qWarning() << "Failed to copy file " << tgtFilePath;
            return false;
        }
    }
    return true;
}

/**
 * Test of complete system using the maildir resource.
 *
 * This test requires the maildir resource installed.
 */
class MaildirResourceTest : public QObject
{
    Q_OBJECT

    QTemporaryDir tempDir;
    QString targetPath;
private slots:
    void initTestCase()
    {
        targetPath = tempDir.path() + "/maildir1/";

        //FIXME initTest only works for the current process,
        //we also have to start resources in test-mode
        // Sink::Test::initTest();
        Sink::Log::setDebugOutputLevel(Sink::Log::Trace);
        MaildirResource::removeFromDisk("org.kde.maildir.instance1");
        Sink::ApplicationDomain::SinkResource resource;
        resource.setProperty("identifier", "org.kde.maildir.instance1");
        resource.setProperty("type", "org.kde.maildir");
        resource.setProperty("path", targetPath);
        Sink::Store::create(resource).exec().waitForFinished();
    }

    void cleanup()
    {
        Sink::ResourceControl::shutdown(QByteArray("org.kde.maildir.instance1")).exec().waitForFinished();
        MaildirResource::removeFromDisk("org.kde.maildir.instance1");
        QDir dir(targetPath);
        dir.removeRecursively();
    }

    void init()
    {
        qDebug();
        qDebug() << "-----------------------------------------";
        qDebug();
        copyRecursively(TESTDATAPATH "/maildir1", targetPath);
        Sink::ResourceControl::start(QByteArray("org.kde.maildir.instance1")).exec().waitForFinished();
    }

    void testListFolders()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto model = Sink::Store::loadModel<Sink::ApplicationDomain::Folder>(query);
        QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(model->rowCount(QModelIndex()), 3);
    }

    void testListFolderTree()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";
        query.parentProperty = "parent";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto model = Sink::Store::loadModel<Sink::ApplicationDomain::Folder>(query);
        QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(model->rowCount(QModelIndex()), 1);
        auto parentIndex = model->index(0, 0, QModelIndex());
        model->fetchMore(parentIndex);
        QTRY_VERIFY(model->data(parentIndex, Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(model->rowCount(parentIndex), 2);
    }

    void testListMailsOfFolder()
    {
        using namespace Sink;
        using namespace Sink::ApplicationDomain;
        // Ensure all local data is processed
        auto query = Query::ResourceFilter("org.kde.maildir.instance1");
        Store::synchronize(query).exec().waitForFinished();
        ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();
        auto result = Store::fetchOne<Folder>(Query::ResourceFilter("org.kde.maildir.instance1") + Query::RequestedProperties(QByteArrayList() << "name"))
                          .then<QList<Mail::Ptr>, Folder>([](const Folder &folder) {
                              Trace() << "Found a folder" << folder.identifier();
                              return Store::fetchAll<Mail>(Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                                                                 << "subject"));
                          })
                          .then<void, QList<Mail::Ptr>>([](const QList<Mail::Ptr> &mails) { QVERIFY(mails.size() >= 1); })
                          .exec();
        result.waitForFinished();
        QVERIFY(!result.errorCode());
    }

    void testMailContent()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";
        query.requestedProperties << "folder"
                                  << "subject"
                                  << "mimeMessage"
                                  << "date";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto mailModel = Sink::Store::loadModel<Sink::ApplicationDomain::Mail>(query);
        QTRY_VERIFY(mailModel->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QVERIFY(mailModel->rowCount(QModelIndex()) >= 1);
        auto mail = mailModel->index(0, 0, QModelIndex()).data(Sink::Store::DomainObjectRole).value<Sink::ApplicationDomain::Mail::Ptr>();
        QVERIFY(!mail->getProperty("subject").toString().isEmpty());
        QVERIFY(!mail->getProperty("mimeMessage").toString().isEmpty());
        QVERIFY(mail->getProperty("date").toDateTime().isValid());

        QFileInfo info(mail->getProperty("mimeMessage").toString());
        QVERIFY(info.exists());
    }


    void testSyncFolderMove()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";
        query.requestedProperties << "name";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto targetPath = tempDir.path() + "/maildir1/";
        QDir dir(targetPath);
        QVERIFY(dir.rename("inbox", "newbox"));

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto model = Sink::Store::loadModel<Sink::ApplicationDomain::Folder>(query);
        QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(model->rowCount(QModelIndex()), 4);
        QCOMPARE(model->match(model->index(0, 0, QModelIndex()), Qt::DisplayRole, QStringLiteral("newbox"), 1).size(), 1);
    }

    void testReSyncMail()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";
        query.requestedProperties << "folder"
                                  << "subject";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto mailModel = Sink::Store::loadModel<Sink::ApplicationDomain::Mail>(query);
        QTRY_VERIFY(mailModel->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(mailModel->rowCount(QModelIndex()), 3);
    }

    void testSyncMailRemoval()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";
        query.requestedProperties << "folder"
                                  << "subject";

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto targetPath = tempDir.path() + "/maildir1/cur/1365777830.R28.localhost.localdomain:2,S";
        QFile file(targetPath);
        QVERIFY(file.remove());

        // Ensure all local data is processed
        Sink::Store::synchronize(query).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto mailModel = Sink::Store::loadModel<Sink::ApplicationDomain::Mail>(query);
        QTRY_VERIFY(mailModel->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(mailModel->rowCount(QModelIndex()), 2);
    }

    void testCreateFolder()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        Sink::ApplicationDomain::Folder folder("org.kde.maildir.instance1");
        folder.setProperty("name", "testCreateFolder");

        Sink::Store::create(folder).exec().waitForFinished();

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto targetPath = tempDir.path() + "/maildir1/testCreateFolder";
        QFileInfo file(targetPath);
        QTRY_VERIFY(file.exists());
        QVERIFY(file.isDir());
    }

    void testRemoveFolder()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";

        auto targetPath = tempDir.path() + "/maildir1/testCreateFolder";

        Sink::ApplicationDomain::Folder folder("org.kde.maildir.instance1");
        folder.setProperty("name", "testCreateFolder");
        Sink::Store::create(folder).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();
        QTRY_VERIFY(QFileInfo(targetPath).exists());

        Sink::Query folderQuery;
        folderQuery.resources << "org.kde.maildir.instance1";
        folderQuery += Sink::Query::PropertyFilter("name", "testCreateFolder");
        auto model = Sink::Store::loadModel<Sink::ApplicationDomain::Folder>(folderQuery);
        QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool());
        QCOMPARE(model->rowCount(QModelIndex()), 1);
        auto createdFolder = model->index(0, 0, QModelIndex()).data(Sink::Store::DomainObjectRole).value<Sink::ApplicationDomain::Folder::Ptr>();

        Sink::Store::remove(*createdFolder).exec().waitForFinished();
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();
        QTRY_VERIFY(!QFileInfo(targetPath).exists());
    }

    void testCreateMail()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto message = KMime::Message::Ptr::create();
        message->subject(true)->fromUnicodeString(QString::fromLatin1("Foobar"), "utf8");
        message->assemble();

        auto mail = Sink::ApplicationDomain::ApplicationDomainType::createEntity<Sink::ApplicationDomain::Mail>("org.kde.maildir.instance1");
        mail.setBlobProperty("mimeMessage", message->encodedContent());
        //FIXME generate accessors
        // mail.setMimeMessage(message->encodedContent());

        Sink::Store::create(mail).exec().waitForFinished();

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        //Ensure extracted properties are up to date.
        auto future = Sink::Store::fetchOne<ApplicationDomain::Mail>(Query::IdentityFilter(mail.identifier()) + Query::RequestedProperties(QByteArrayList() << "subject"))
            .then<void, ApplicationDomain::Mail>([](const ApplicationDomain::Mail &mail) {
                QCOMPARE(mail.getProperty("subject").toString(), QString::fromLatin1("Foobar"));
            }).exec();
        future.waitForFinished();

        auto targetPath = tempDir.path() + "/maildir1/cur";
        QDir dir(targetPath);
        dir.setFilter(QDir::Files);
        QTRY_COMPARE(dir.count(), static_cast<unsigned int>(2));
        QFile file(targetPath + "/" + dir.entryList().last());
        QVERIFY(file.open(QIODevice::ReadOnly));
        KMime::Message m;
        m.setContent(file.readAll());
        m.parse();
        QCOMPARE(m.subject(true)->asUnicodeString(), QString::fromLatin1("Foobar"));
    }

    void testCreateMailInFolder()
    {
        auto query = Sink::Query::ResourceFilter("org.kde.maildir.instance1");

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        //TODO
        //create folder
        //create mail in folder
        //ensure mail is in folder
        //
        auto folder = Sink::ApplicationDomain::ApplicationDomainType::createEntity<Sink::ApplicationDomain::Folder>("org.kde.maildir.instance1");
        folder.setProperty("name", "newfolder");

        Sink::Store::create(folder).exec().waitForFinished();

        auto message = KMime::Message::Ptr::create();
        message->subject(true)->fromUnicodeString(QString::fromLatin1("Foobar"), "utf8");
        message->assemble();

        auto mail = Sink::ApplicationDomain::ApplicationDomainType::createEntity<Sink::ApplicationDomain::Mail>("org.kde.maildir.instance1");
        mail.setBlobProperty("mimeMessage", message->encodedContent());
        mail.setProperty("folder", folder);

        Sink::Store::create(mail).exec().waitForFinished();
        // .then()
        // .exec().waitForFinished();
        //
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto future = Sink::Store::fetchOne<ApplicationDomain::Mail>(Query::IdentityFilter(mail.identifier()) + Query::RequestedProperties(QByteArrayList() << "mimeMessage" << "folder"))
            .then<void, ApplicationDomain::Mail>([folder](const ApplicationDomain::Mail &mail) {
                // qDebug() << "Retrieved draft: " << mail.getProperty("folder") << mail.identifier() << mail.getProperty("mimeMessage").toString();
                QCOMPARE(mail.getProperty("folder").toByteArray(), folder.identifier());
            }).exec();
        future.waitForFinished();
        if (future.errorCode()) {
            qWarning() << future.errorCode() << future.errorMessage();
        }
        QVERIFY(!future.errorCode());
        auto future2 = ResourceControl::inspect<ApplicationDomain::Mail>(ResourceControl::Inspection::ExistenceInspection(mail, false)).exec();
        future2.waitForFinished();
        QVERIFY(!future2.errorCode());

        auto targetPath = tempDir.path() + "/maildir1/newfolder/cur";
        QDir dir(targetPath);
        dir.setFilter(QDir::Files);
        QCOMPARE(dir.count(), static_cast<unsigned int>(1));
    }

    void testRemoveMail()
    {
        using namespace Sink;
        using namespace Sink::ApplicationDomain;

        auto query = Query::ResourceFilter("org.kde.maildir.instance1");
        Store::synchronize(query).exec().waitForFinished();
        ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto result = Store::fetchOne<Folder>(
                          Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name"))
                          .then<void, KAsync::Job<void>, Folder>([query](const Folder &folder) {
                              return Store::fetchAll<Mail>(Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                                                                 << "subject"))
                                  .then<void, KAsync::Job<void>, QList<Mail::Ptr>>([query](const QList<Mail::Ptr> &mails) {
                                      ASYNCCOMPARE(mails.size(), 1);
                                      auto mail = mails.first();

                                      return Store::remove(*mail)
                                          .then(ResourceControl::flushReplayQueue(query.resources)) // The change needs to be replayed already
                                          .then(ResourceControl::inspect<Mail>(ResourceControl::Inspection::ExistenceInspection(*mail, false)));
                                  });
                          })
                          .exec();
        result.waitForFinished();
        QVERIFY(!result.errorCode());
    }

    void testMarkMailAsRead()
    {
        using namespace Sink;
        using namespace Sink::ApplicationDomain;

        auto query = Query::ResourceFilter("org.kde.maildir.instance1");
        Store::synchronize(query).exec().waitForFinished();
        ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        Folder f;

        auto result = Store::fetchOne<Folder>(
                          Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name"))
                          .then<void, KAsync::Job<void>, Folder>([query, &f](const Folder &folder) {
                              f = folder;
                              return Store::fetchAll<Mail>(Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", folder) +
                                                           Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                       << "subject"))
                                  .then<void, KAsync::Job<void>, QList<Mail::Ptr>>([query](const QList<Mail::Ptr> &mails) {
                                      ASYNCCOMPARE(mails.size(), 1);
                                      auto mail = mails.first();
                                      mail->setProperty("unread", true);
                                      return Store::modify(*mail)
                                          .then<void>(ResourceControl::flushReplayQueue(query.resources)) // The change needs to be replayed already
                                          .then(ResourceControl::inspect<Mail>(ResourceControl::Inspection::PropertyInspection(*mail, "unread", true)))
                                          .then(ResourceControl::inspect<Mail>(ResourceControl::Inspection::PropertyInspection(*mail, "subject", mail->getProperty("subject"))));
                                  });
                          })
                          .exec();
        result.waitForFinished();
        QVERIFY(!result.errorCode());

        // Verify that we can still query for all relevant information
        auto result2 = Store::fetchAll<Mail>(
                           Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", f) + Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                                                                                 << "subject"
                                                                                                                                                                 << "mimeMessage"
                                                                                                                                                                 << "unread"))
                           .then<void, KAsync::Job<void>, QList<Mail::Ptr>>([](const QList<Mail::Ptr> &mails) {
                               ASYNCCOMPARE(mails.size(), 1);
                               auto mail = mails.first();
                               ASYNCVERIFY(!mail->getProperty("subject").toString().isEmpty());
                               ASYNCCOMPARE(mail->getProperty("unread").toBool(), true);
                               ASYNCVERIFY(QFileInfo(mail->getProperty("mimeMessage").toString()).exists());
                               return KAsync::null<void>();
                           })
                           .exec();
        result2.waitForFinished();
        QVERIFY(!result2.errorCode());
    }

    void testEditMail()
    {
        using namespace Sink;
        using namespace Sink::ApplicationDomain;

        auto query = Query::ResourceFilter("org.kde.maildir.instance1");
        Store::synchronize(query).exec().waitForFinished();
        ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        Folder f;

        auto result = Store::fetchOne<Folder>(
                          Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name"))
                          .then<void, KAsync::Job<void>, Folder>([query, &f](const Folder &folder) {
                              f = folder;
                              return Store::fetchAll<Mail>(Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", folder) +
                                                           Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                       << "subject" << "mimeMessage"))
                                  .then<void, KAsync::Job<void>, QList<Mail::Ptr>>([query](const QList<Mail::Ptr> &mails) {
                                      ASYNCCOMPARE(mails.size(), 1);
                                      auto mail = mails.first();
                                      auto message = KMime::Message::Ptr::create();
                                      message->subject(true)->fromUnicodeString("Test1", "utf8");
                                      message->assemble();
                                      mail->setMimeMessage(message->encodedContent());
                                      return Store::modify(*mail);
                                  });
                          })
                          .exec();
        result.waitForFinished();
        QVERIFY(!result.errorCode());

        ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        // Verify that we can still query for all relevant information
        auto result2 = Store::fetchAll<Mail>(
                           Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", f) + Query::RequestedProperties(QByteArrayList() << "folder"
                                                                                                                                                                 << "subject"
                                                                                                                                                                 << "mimeMessage"
                                                                                                                                                                 << "unread"))
                           .then<void, KAsync::Job<void>, QList<Mail::Ptr>>([](const QList<Mail::Ptr> &mails) {
                               ASYNCCOMPARE(mails.size(), 1);
                               auto mail = mails.first();
                               ASYNCCOMPARE(mail->getProperty("subject").toString(), QString("Test1"));
                               ASYNCVERIFY(QFileInfo(mail->getMimeMessagePath()).exists());
                               return KAsync::null<void>();
                           })
                           .exec();
        result2.waitForFinished();
        QVERIFY(!result2.errorCode());

        //Ensure we didn't leave a stale message behind
        auto targetPath = tempDir.path() + "/maildir1/cur";
        QDir dir(targetPath);
        dir.setFilter(QDir::Files);
        QTRY_COMPARE(dir.count(), static_cast<unsigned int>(1));
    }

    void testCreateDraft()
    {
        Sink::Query query;
        query.resources << "org.kde.maildir.instance1";

        Sink::Store::synchronize(query).exec().waitForFinished();
        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        auto message = KMime::Message::Ptr::create();
        message->subject(true)->fromUnicodeString(QString::fromLatin1("Foobar"), "utf8");
        message->assemble();

        auto mail = Sink::ApplicationDomain::ApplicationDomainType::createEntity<Sink::ApplicationDomain::Mail>("org.kde.maildir.instance1");
        // Sink::ApplicationDomain::Mail::create("org.kde.maildir.instance1");
        mail.setBlobProperty("mimeMessage", message->encodedContent());
        mail.setProperty("draft", true);

        Sink::Store::create(mail).exec().waitForFinished();

        // Ensure all local data is processed
        Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished();

        QByteArray folderIdentifier;
        auto future = Sink::Store::fetchOne<ApplicationDomain::Mail>(Query::IdentityFilter(mail.identifier()) + Query::RequestedProperties(QByteArrayList() << "mimeMessage" << "folder"))
            .then<void, ApplicationDomain::Mail>([&](const ApplicationDomain::Mail &mail) {
                folderIdentifier = mail.getProperty("folder").toByteArray();
                QVERIFY(!folderIdentifier.isEmpty());
            }).exec();
        future.waitForFinished();
        if (future.errorCode()) {
            qWarning() << future.errorCode() << future.errorMessage();
        }
        QVERIFY(!future.errorCode());

        //Ensure we can also query by folder
        Sink::Store::fetchAll<ApplicationDomain::Mail>(Query::PropertyFilter("folder", folderIdentifier))
            .then<void, QList<ApplicationDomain::Mail::Ptr> >([&](const QList<ApplicationDomain::Mail::Ptr> &mails) {
                bool found = false;
                for (const auto m : mails) {
                    if (m->identifier() == mail.identifier()) {
                        found = true;
                    }
                }
                QVERIFY(found);
            }).exec().waitForFinished();
    }
};

QTEST_MAIN(MaildirResourceTest)
#include "maildirresourcetest.moc"