File indexing completed on 2024-12-01 04:35:24

0001 /*
0002    SPDX-FileCopyrightText: 2020 David Faure <faure@kde.org>
0003 
0004    SPDX-License-Identifier: LGPL-2.0-or-later
0005 */
0006 
0007 #include "messagecachetest.h"
0008 #include "chat/getmessagejob.h"
0009 #include "messagecache.h"
0010 #include "messages/message.h"
0011 
0012 #include <QJsonDocument>
0013 #include <QSignalSpy>
0014 #include <QTest>
0015 #include <QTimer>
0016 
0017 QTEST_GUILESS_MAIN(MessageCacheTest)
0018 
0019 class MyMessageCache : public MessageCache
0020 {
0021 public:
0022     using MessageCache::MessageCache;
0023     int jobsStarted() const
0024     {
0025         return mJobStarted;
0026     }
0027 
0028 protected:
0029     bool startJob(RocketChatRestApi::RestApiAbstractJob *job) override
0030     {
0031         if (auto getMsgJob = qobject_cast<RocketChatRestApi::GetMessageJob *>(job)) {
0032             QTimer::singleShot(100, this, [getMsgJob]() {
0033                 const QByteArray content =
0034                     "{ \"message\": "
0035                     "{ \"msg\": \"message foo\","
0036                     "  \"_id\": \"Co6LnNbu5TYcXPuMG\" } }";
0037                 const QJsonDocument doc = QJsonDocument::fromJson(content);
0038                 Q_EMIT getMsgJob->getMessageDone(doc.object(), getMsgJob->messageId(), getMsgJob->roomId());
0039             });
0040             ++mJobStarted;
0041             return true;
0042         }
0043         return false;
0044     }
0045 
0046 private:
0047     int mJobStarted = 0;
0048 };
0049 
0050 MessageCacheTest::MessageCacheTest(QObject *parent)
0051     : QObject(parent)
0052 {
0053 }
0054 
0055 void MessageCacheTest::shouldLoadSingleMessage()
0056 {
0057     // GIVEN
0058     MyMessageCache cache(nullptr);
0059     const QString messageId = QStringLiteral("Co6LnNbu5TYcXPuMG");
0060     QSignalSpy loadedSpy(&cache, &MessageCache::messageLoaded);
0061 
0062     // WHEN
0063     Message *msg = cache.messageForId(messageId);
0064     QVERIFY(!msg);
0065     msg = cache.messageForId(messageId);
0066     QVERIFY(!msg);
0067 
0068     // THEN
0069     QCOMPARE(cache.jobsStarted(), 1);
0070     QVERIFY(loadedSpy.isEmpty());
0071     QVERIFY(loadedSpy.wait());
0072     msg = cache.messageForId(messageId);
0073     QVERIFY(msg);
0074     QCOMPARE(msg->messageId(), messageId);
0075     QCOMPARE(cache.jobsStarted(), 1);
0076 }
0077 
0078 #include "moc_messagecachetest.cpp"