From 4d9746c828558c9f872e0aed52442863affb25d5 Mon Sep 17 00:00:00 2001 From: Christian Mollekopf Date: Thu, 3 Mar 2016 09:01:05 +0100 Subject: Fromatted the whole codebase with clang-format. clang-format -i */**{.cpp,.h} --- tests/clientapitest.cpp | 76 +++--- .../databasepopulationandfacadequerybenchmark.cpp | 61 +++-- tests/domainadaptortest.cpp | 12 +- tests/dummyresourcebenchmark.cpp | 78 +++---- tests/dummyresourcetest.cpp | 35 ++- tests/dummyresourcewritebenchmark.cpp | 32 +-- tests/genericfacadetest.cpp | 24 +- tests/genericresourcebenchmark.cpp | 22 +- tests/genericresourcetest.cpp | 6 +- tests/getrssusage.cpp | 106 ++++----- tests/getrssusage.h | 2 +- tests/indextest.cpp | 23 +- tests/inspectiontest.cpp | 2 +- tests/maildirresourcetest.cpp | 205 ++++++++-------- tests/maildirsyncbenchmark.cpp | 12 +- tests/mailquerybenchmark.cpp | 45 ++-- tests/messagequeuetest.cpp | 85 +++---- tests/modelinteractivitytest.cpp | 27 ++- tests/pipelinebenchmark.cpp | 21 +- tests/pipelinetest.cpp | 52 +++-- tests/querytest.cpp | 72 +++--- tests/resourcecommunicationtest.cpp | 34 +-- tests/storagebenchmark.cpp | 34 +-- tests/storagetest.cpp | 259 ++++++++++----------- tests/testimplementations.h | 45 ++-- 25 files changed, 669 insertions(+), 701 deletions(-) (limited to 'tests') diff --git a/tests/clientapitest.cpp b/tests/clientapitest.cpp index 879ffc4..172232f 100644 --- a/tests/clientapitest.cpp +++ b/tests/clientapitest.cpp @@ -13,34 +13,41 @@ template class DummyResourceFacade : public Sink::StoreFacade { public: - static std::shared_ptr > registerFacade(const QByteArray &instanceIdentifier = QByteArray()) + static std::shared_ptr> registerFacade(const QByteArray &instanceIdentifier = QByteArray()) { - static QMap > > map; - auto facade = std::make_shared >(); + static QMap>> map; + auto facade = std::make_shared>(); map.insert(instanceIdentifier, facade); bool alwaysReturnFacade = instanceIdentifier.isEmpty(); - Sink::FacadeFactory::instance().registerFacade >("dummyresource", - [alwaysReturnFacade](const QByteArray &instanceIdentifier) { - if (alwaysReturnFacade) { - return map.value(QByteArray()); - } - return map.value(instanceIdentifier); + Sink::FacadeFactory::instance().registerFacade>("dummyresource", [alwaysReturnFacade](const QByteArray &instanceIdentifier) { + if (alwaysReturnFacade) { + return map.value(QByteArray()); } - ); + return map.value(instanceIdentifier); + }); return facade; } ~DummyResourceFacade(){}; - KAsync::Job create(const T &domainObject) Q_DECL_OVERRIDE { return KAsync::null(); }; - KAsync::Job modify(const T &domainObject) Q_DECL_OVERRIDE { return KAsync::null(); }; - KAsync::Job remove(const T &domainObject) Q_DECL_OVERRIDE { return KAsync::null(); }; - QPair, typename Sink::ResultEmitter::Ptr > load(const Sink::Query &query) Q_DECL_OVERRIDE + KAsync::Job create(const T &domainObject) Q_DECL_OVERRIDE + { + return KAsync::null(); + }; + KAsync::Job modify(const T &domainObject) Q_DECL_OVERRIDE + { + return KAsync::null(); + }; + KAsync::Job remove(const T &domainObject) Q_DECL_OVERRIDE + { + return KAsync::null(); + }; + QPair, typename Sink::ResultEmitter::Ptr> load(const Sink::Query &query) Q_DECL_OVERRIDE { auto resultProvider = new Sink::ResultProvider(); resultProvider->onDone([resultProvider]() { Trace() << "Result provider is done"; delete resultProvider; }); - //We have to do it this way, otherwise we're not setting the fetcher right + // We have to do it this way, otherwise we're not setting the fetcher right auto emitter = resultProvider->emitter(); resultProvider->setFetcher([query, resultProvider, this](const typename T::Ptr &parent) { @@ -60,8 +67,7 @@ public: } resultProvider->initialResultSetComplete(parent); }); - auto job = KAsync::start([query, resultProvider]() { - }); + auto job = KAsync::start([query, resultProvider]() {}); mResultProvider = resultProvider; return qMakePair(job, emitter); } @@ -73,7 +79,7 @@ public: /** * Test of the client api implementation. - * + * * This test works with injected dummy facades and thus doesn't write to storage. */ class ClientAPITest : public QObject @@ -113,7 +119,7 @@ private slots: QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); } - //TODO: This test doesn't belong to this testsuite + // TODO: This test doesn't belong to this testsuite void resourceManagement() { ResourceConfig::clear(); @@ -158,13 +164,13 @@ private slots: void testModelNested() { auto facade = DummyResourceFacade::registerFacade(); - auto folder = QSharedPointer::create("resource", "id", 0, QSharedPointer::create()); + auto folder = QSharedPointer::create("resource", "id", 0, QSharedPointer::create()); auto subfolder = QSharedPointer::create("resource", "subId", 0, QSharedPointer::create()); subfolder->setProperty("parent", "id"); facade->results << folder << subfolder; ResourceConfig::addResource("dummyresource.instance1", "dummyresource"); - //Test + // Test Sink::Query query; query.resources << "dummyresource.instance1"; query.liveQuery = false; @@ -181,13 +187,13 @@ private slots: void testModelSignals() { auto facade = DummyResourceFacade::registerFacade(); - auto folder = QSharedPointer::create("resource", "id", 0, QSharedPointer::create()); + auto folder = QSharedPointer::create("resource", "id", 0, QSharedPointer::create()); auto subfolder = QSharedPointer::create("resource", "subId", 0, QSharedPointer::create()); subfolder->setProperty("parent", "id"); facade->results << folder << subfolder; ResourceConfig::addResource("dummyresource.instance1", "dummyresource"); - //Test + // Test Sink::Query query; query.resources << "dummyresource.instance1"; query.liveQuery = false; @@ -203,13 +209,14 @@ private slots: void testModelNestedLive() { auto facade = DummyResourceFacade::registerFacade(); - auto folder = QSharedPointer::create("dummyresource.instance1", "id", 0, QSharedPointer::create()); - auto subfolder = QSharedPointer::create("dummyresource.instance1", "subId", 0, QSharedPointer::create()); + auto folder = QSharedPointer::create("dummyresource.instance1", "id", 0, QSharedPointer::create()); + auto subfolder = + QSharedPointer::create("dummyresource.instance1", "subId", 0, QSharedPointer::create()); subfolder->setProperty("parent", "id"); facade->results << folder << subfolder; ResourceConfig::addResource("dummyresource.instance1", "dummyresource"); - //Test + // Test Sink::Query query; query.resources << "dummyresource.instance1"; query.liveQuery = true; @@ -222,7 +229,7 @@ private slots: auto resultProvider = facade->mResultProvider; - //Test new toplevel folder + // Test new toplevel folder { QSignalSpy rowsInsertedSpy(model.data(), SIGNAL(rowsInserted(const QModelIndex &, int, int))); auto folder2 = QSharedPointer::create("resource", "id2", 0, QSharedPointer::create()); @@ -232,7 +239,7 @@ private slots: QCOMPARE(rowsInsertedSpy.at(0).at(0).value(), QModelIndex()); } - //Test changed name + // Test changed name { QSignalSpy dataChanged(model.data(), SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &, const QVector &))); folder->setProperty("subject", "modifiedSubject"); @@ -241,7 +248,7 @@ private slots: QTRY_COMPARE(dataChanged.count(), 1); } - //Test removal + // Test removal { QSignalSpy rowsRemovedSpy(model.data(), SIGNAL(rowsRemoved(const QModelIndex &, int, int))); folder->setProperty("subject", "modifiedSubject"); @@ -250,7 +257,7 @@ private slots: QTRY_COMPARE(rowsRemovedSpy.count(), 1); } - //TODO: A modification can also be a move + // TODO: A modification can also be a move } void testLoadMultiResource() @@ -274,7 +281,7 @@ private slots: }); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(QModelIndex()), 2); - //Ensure children fetched is only emitted once (when all resources are done) + // Ensure children fetched is only emitted once (when all resources are done) QTest::qWait(50); QCOMPARE(childrenFetchedCount, 1); } @@ -291,15 +298,12 @@ private slots: bool gotValue = false; auto result = Sink::Store::fetchOne(query) - .then([&gotValue](const Sink::ApplicationDomain::Event &event) { - gotValue = true; - }).exec(); + .then([&gotValue](const Sink::ApplicationDomain::Event &event) { gotValue = true; }) + .exec(); result.waitForFinished(); QVERIFY(!result.errorCode()); QVERIFY(gotValue); } - - }; QTEST_MAIN(ClientAPITest) diff --git a/tests/databasepopulationandfacadequerybenchmark.cpp b/tests/databasepopulationandfacadequerybenchmark.cpp index 16537c0..4e886af 100644 --- a/tests/databasepopulationandfacadequerybenchmark.cpp +++ b/tests/databasepopulationandfacadequerybenchmark.cpp @@ -23,7 +23,7 @@ /** * Benchmark read performance of the facade implementation. - * + * * The memory used should grow linearly with the number of retrieved entities. * The memory used should be independent from the database size, after accounting for the memory mapped db. */ @@ -39,7 +39,7 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject void populateDatabase(int count) { Sink::Storage(Sink::storageLocation(), "identifier", Sink::Storage::ReadWrite).removeFromDisk(); - //Setup + // Setup auto domainTypeAdaptorFactory = QSharedPointer::create(); { Sink::Storage storage(Sink::storageLocation(), identifier, Sink::Storage::ReadWrite); @@ -57,7 +57,7 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject domainObject->setProperty("attachment", attachment); flatbuffers::FlatBufferBuilder fbb; domainTypeAdaptorFactory->createBuffer(*domainObject, fbb); - const auto buffer = QByteArray::fromRawData(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); + const auto buffer = QByteArray::fromRawData(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); const auto key = QUuid::createUuid().toString().toLatin1(); db.write(key, buffer); bufferSizeTotal += buffer.size(); @@ -72,15 +72,15 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject auto size = db.getSize(); auto onDisk = storage.diskUsage(); auto writeAmplification = static_cast(onDisk) / static_cast(bufferSizeTotal); - std::cout << "Database size [kb]: " << size/1024 << std::endl; - std::cout << "On disk [kb]: " << onDisk/1024 << std::endl; - std::cout << "Buffer size total [kb]: " << bufferSizeTotal/1024 << std::endl; - std::cout << "Key size total [kb]: " << keysSizeTotal/1024 << std::endl; - std::cout << "Data size total [kb]: " << dataSizeTotal/1024 << std::endl; + std::cout << "Database size [kb]: " << size / 1024 << std::endl; + std::cout << "On disk [kb]: " << onDisk / 1024 << std::endl; + std::cout << "Buffer size total [kb]: " << bufferSizeTotal / 1024 << std::endl; + std::cout << "Key size total [kb]: " << keysSizeTotal / 1024 << std::endl; + std::cout << "Data size total [kb]: " << dataSizeTotal / 1024 << std::endl; std::cout << "Write amplification: " << writeAmplification << std::endl; - //The buffer has an overhead, but with a reasonable attachment size it should be relatively small - //A write amplification of 2 should be the worst case + // The buffer has an overhead, but with a reasonable attachment size it should be relatively small + // A write amplification of 2 should be the worst case QVERIFY(writeAmplification < 2); } } @@ -91,13 +91,14 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject Sink::Query query; query.liveQuery = false; - query.requestedProperties << "uid" << "summary"; + query.requestedProperties << "uid" + << "summary"; - //Benchmark + // Benchmark QTime time; time.start(); - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); TestResourceFacade facade(identifier, resourceAccess); @@ -105,13 +106,9 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject ret.first.exec().waitForFinished(); auto emitter = ret.second; QList list; - emitter->onAdded([&list](const Sink::ApplicationDomain::Event::Ptr &event) { - list << event; - }); + emitter->onAdded([&list](const Sink::ApplicationDomain::Event::Ptr &event) { list << event; }); bool done = false; - emitter->onInitialResultSetComplete([&done](const Sink::ApplicationDomain::Event::Ptr &event) { - done = true; - }); + emitter->onInitialResultSetComplete([&done](const Sink::ApplicationDomain::Event::Ptr &event) { done = true; }); emitter->fetch(Sink::ApplicationDomain::Event::Ptr()); QTRY_VERIFY(done); QCOMPARE(list.size(), count); @@ -120,35 +117,35 @@ class DatabasePopulationAndFacadeQueryBenchmark : public QObject const auto finalRss = getCurrentRSS(); const auto rssGrowth = finalRss - startingRss; - //Since the database is memory mapped it is attributted to the resident set size. + // Since the database is memory mapped it is attributted to the resident set size. const auto rssWithoutDb = finalRss - Sink::Storage(Sink::storageLocation(), identifier, Sink::Storage::ReadWrite).diskUsage(); - const auto peakRss = getPeakRSS(); - //How much peak deviates from final rss in percent (should be around 0) - const auto percentageRssError = static_cast(peakRss - finalRss)*100.0/static_cast(finalRss); - auto rssGrowthPerEntity = rssGrowth/count; + const auto peakRss = getPeakRSS(); + // How much peak deviates from final rss in percent (should be around 0) + const auto percentageRssError = static_cast(peakRss - finalRss) * 100.0 / static_cast(finalRss); + auto rssGrowthPerEntity = rssGrowth / count; std::cout << "Loaded " << list.size() << " results." << std::endl; std::cout << "The query took [ms]: " << elapsed << std::endl; - std::cout << "Current Rss usage [kb]: " << finalRss/1024 << std::endl; - std::cout << "Peak Rss usage [kb]: " << peakRss/1024 << std::endl; - std::cout << "Rss growth [kb]: " << rssGrowth/1024 << std::endl; + std::cout << "Current Rss usage [kb]: " << finalRss / 1024 << std::endl; + std::cout << "Peak Rss usage [kb]: " << peakRss / 1024 << std::endl; + std::cout << "Rss growth [kb]: " << rssGrowth / 1024 << std::endl; std::cout << "Rss growth per entity [byte]: " << rssGrowthPerEntity << std::endl; - std::cout << "Rss without db [kb]: " << rssWithoutDb/1024 << std::endl; + std::cout << "Rss without db [kb]: " << rssWithoutDb / 1024 << std::endl; std::cout << "Percentage error: " << percentageRssError << std::endl; HAWD::Dataset dataset("facade_query", mHawdState); HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", list.size()); - row.setValue("queryResultPerMs", (qreal)list.size()/elapsed); + row.setValue("queryResultPerMs", (qreal)list.size() / elapsed); dataset.insertRow(row); HAWD::Formatter::print(dataset); - mTimePerEntity << static_cast(elapsed)/static_cast(count); + mTimePerEntity << static_cast(elapsed) / static_cast(count); mRssGrowthPerEntity << rssGrowthPerEntity; QVERIFY(percentageRssError < 10); - //TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, - //so it doesn't look like that memory is being duplicated. + // TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, + // so it doesn't look like that memory is being duplicated. QVERIFY(rssGrowthPerEntity < 3300); // Print memory layout, RSS is what is in memory diff --git a/tests/domainadaptortest.cpp b/tests/domainadaptortest.cpp index 5939a31..ff75d21 100644 --- a/tests/domainadaptortest.cpp +++ b/tests/domainadaptortest.cpp @@ -54,7 +54,7 @@ private slots: void testAdaptor() { - //Create entity buffer + // Create entity buffer flatbuffers::FlatBufferBuilder metadataFbb; auto metadataBuilder = Sink::MetadataBuilder(metadataFbb); metadataBuilder.add_revision(1); @@ -75,19 +75,19 @@ private slots: Sink::ApplicationDomain::Buffer::FinishEventBuffer(m_fbb, buffer); flatbuffers::FlatBufferBuilder fbb; - Sink::EntityBuffer::assembleEntityBuffer(fbb, metadataFbb.GetBufferPointer(), metadataFbb.GetSize(), m_fbb.GetBufferPointer(), m_fbb.GetSize(), m_fbb.GetBufferPointer(), m_fbb.GetSize()); + Sink::EntityBuffer::assembleEntityBuffer( + fbb, metadataFbb.GetBufferPointer(), metadataFbb.GetSize(), m_fbb.GetBufferPointer(), m_fbb.GetSize(), m_fbb.GetBufferPointer(), m_fbb.GetSize()); - //Extract entity buffer + // Extract entity buffer { - std::string data(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); - Sink::EntityBuffer buffer((void*)(data.data()), data.size()); + std::string data(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); + Sink::EntityBuffer buffer((void *)(data.data()), data.size()); TestFactory factory; auto adaptor = factory.createAdaptor(buffer.entity()); QCOMPARE(adaptor->getProperty("summary").toString(), QString("summary1")); } } - }; QTEST_MAIN(DomainAdaptorTest) diff --git a/tests/dummyresourcebenchmark.cpp b/tests/dummyresourcebenchmark.cpp index 77b87fb..124abc1 100644 --- a/tests/dummyresourcebenchmark.cpp +++ b/tests/dummyresourcebenchmark.cpp @@ -44,40 +44,38 @@ private slots: { } - static KAsync::Job waitForCompletion(QList > &futures) + static KAsync::Job waitForCompletion(QList> &futures) { auto context = new QObject; return KAsync::start([futures, context](KAsync::Future &future) { - const auto total = futures.size(); - auto count = QSharedPointer::create(); - int i = 0; - for (KAsync::Future subFuture : futures) { - i++; - if (subFuture.isFinished()) { - *count += 1; - continue; - } - //FIXME bind lifetime all watcher to future (repectively the main job - auto watcher = QSharedPointer >::create(); - QObject::connect(watcher.data(), &KAsync::FutureWatcher::futureReady, - [count, total, &future](){ - *count += 1; - if (*count == total) { - future.setFinished(); - } - }); - watcher->setFuture(subFuture); - context->setProperty(QString("future%1").arg(i).toLatin1().data(), QVariant::fromValue(watcher)); - } - }).then([context]() { - delete context; - }); + const auto total = futures.size(); + auto count = QSharedPointer::create(); + int i = 0; + for (KAsync::Future subFuture : futures) { + i++; + if (subFuture.isFinished()) { + *count += 1; + continue; + } + // FIXME bind lifetime all watcher to future (repectively the main job + auto watcher = QSharedPointer>::create(); + QObject::connect(watcher.data(), &KAsync::FutureWatcher::futureReady, [count, total, &future]() { + *count += 1; + if (*count == total) { + future.setFinished(); + } + }); + watcher->setFuture(subFuture); + context->setProperty(QString("future%1").arg(i).toLatin1().data(), QVariant::fromValue(watcher)); + } + }) + .then([context]() { delete context; }); } - //Ensure we can process a command in less than 0.1s + // Ensure we can process a command in less than 0.1s void testCommandResponsiveness() { - //Test responsiveness including starting the process. + // Test responsiveness including starting the process. Sink::Store::removeDataFromDisk("org.kde.dummy.instance1").exec().waitForFinished(); QTime time; @@ -100,7 +98,7 @@ private slots: Sink::Store::create(event).exec(); - //Wait for notification + // Wait for notification QTRY_VERIFY(gotNotification); QVERIFY2(duration < 100, QString::fromLatin1("Processing a create command took more than 100ms: %1").arg(duration).toLatin1()); @@ -114,7 +112,7 @@ private slots: QTime time; time.start(); - QList > waitCondition; + QList> waitCondition; for (int i = 0; i < num; i++) { Sink::ApplicationDomain::Event event("org.kde.dummy.instance1"); event.setProperty("uid", "testuid"); @@ -125,7 +123,7 @@ private slots: waitForCompletion(waitCondition).exec().waitForFinished(); auto appendTime = time.elapsed(); - //Ensure everything is processed + // Ensure everything is processed { Sink::Query query; query.resources << "org.kde.dummy.instance1"; @@ -137,13 +135,13 @@ private slots: HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", num); - row.setValue("append", (qreal)num/appendTime); - row.setValue("total", (qreal)num/allProcessedTime); + row.setValue("append", (qreal)num / appendTime); + row.setValue("total", (qreal)num / allProcessedTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); auto diskUsage = DummyResource::diskUsage("org.kde.dummy.instance1"); - qDebug() << "Database size [kb]: " << diskUsage/1024; + qDebug() << "Database size [kb]: " << diskUsage / 1024; // Print memory layout, RSS is what is in memory // std::system("exec pmap -x \"$PPID\""); @@ -153,7 +151,7 @@ private slots: { QTime time; time.start(); - //Measure query + // Measure query { time.start(); Sink::Query query; @@ -168,7 +166,7 @@ private slots: HAWD::Dataset dataset("dummy_query_by_uid", m_hawdState); HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", num); - row.setValue("read", (qreal)num/queryTime); + row.setValue("read", (qreal)num / queryTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); } @@ -220,7 +218,7 @@ private slots: } auto appendTime = time.elapsed(); - //Wait until all messages have been processed + // Wait until all messages have been processed resource.processAllMessages().exec().waitForFinished(); auto allProcessedTime = time.elapsed(); @@ -229,8 +227,8 @@ private slots: HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", num); - row.setValue("append", (qreal)num/appendTime); - row.setValue("total", (qreal)num/allProcessedTime); + row.setValue("append", (qreal)num / appendTime); + row.setValue("total", (qreal)num / allProcessedTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); @@ -250,7 +248,7 @@ private slots: static flatbuffers::FlatBufferBuilder fbb; fbb.Clear(); - //This is the resource buffer type and not the domain type + // This is the resource buffer type and not the domain type auto entityId = fbb.CreateString(""); auto type = fbb.CreateString("event"); // auto delta = fbb.CreateVector(entityFbb.GetBufferPointer(), entityFbb.GetSize()); @@ -260,7 +258,7 @@ private slots: } } - //This allows to run individual parts without doing a cleanup, but still cleaning up normally + // This allows to run individual parts without doing a cleanup, but still cleaning up normally void testCleanupForCompleteTest() { Sink::Store::removeDataFromDisk("org.kde.dummy.instance1").exec().waitForFinished(); diff --git a/tests/dummyresourcetest.cpp b/tests/dummyresourcetest.cpp index 8b5a8fa..33304e1 100644 --- a/tests/dummyresourcetest.cpp +++ b/tests/dummyresourcetest.cpp @@ -14,7 +14,7 @@ /** * Test of complete system using the dummy resource. - * + * * This test requires the dummy resource installed. */ class DummyResourceTest : public QObject @@ -65,7 +65,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); query.propertyFilter.insert("uid", "testuid"); @@ -89,7 +89,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); query.propertyFilter.insert("uid", "testuid"); @@ -117,7 +117,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); query.propertyFilter.insert("summary", "summaryValue2"); @@ -135,7 +135,7 @@ private slots: auto pipeline = QSharedPointer::create("org.kde.dummy.instance1"); DummyResource resource("org.kde.dummy.instance1", pipeline); auto job = resource.synchronizeWithSource(); - //TODO pass in optional timeout? + // TODO pass in optional timeout? auto future = job.exec(); future.waitForFinished(); QVERIFY(!future.errorCode()); @@ -150,7 +150,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -167,7 +167,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -191,10 +191,10 @@ private slots: query.resources << "org.kde.dummy.instance1"; query.propertyFilter.insert("uid", "testuid"); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //Test create + // Test create Sink::ApplicationDomain::Event event2; { auto model = Sink::Store::loadModel(query); @@ -210,10 +210,10 @@ private slots: event2.setProperty("summary", "summaryValue2"); Sink::Store::modify(event2).exec().waitForFinished(); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //Test modify + // Test modify { auto model = Sink::Store::loadModel(query); QTRY_COMPARE(model->rowCount(QModelIndex()), 1); @@ -225,10 +225,10 @@ private slots: Sink::Store::remove(event2).exec().waitForFinished(); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //Test remove + // Test remove { auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); @@ -253,7 +253,7 @@ private slots: event.setProperty("summary", "summaryValue"); Sink::Store::create(event).exec().waitForFinished(); - //Test create + // Test create Sink::ApplicationDomain::Event event2; { QTRY_COMPARE(model->rowCount(QModelIndex()), 1); @@ -267,9 +267,9 @@ private slots: event2.setProperty("summary", "summaryValue2"); Sink::Store::modify(event2).exec().waitForFinished(); - //Test modify + // Test modify { - //TODO wait for a change signal + // TODO wait for a change signal QTRY_COMPARE(model->rowCount(QModelIndex()), 1); auto value = model->index(0, 0, QModelIndex()).data(Sink::Store::DomainObjectRole).value(); QCOMPARE(value->getProperty("uid").toByteArray(), QByteArray("testuid")); @@ -278,12 +278,11 @@ private slots: Sink::Store::remove(event2).exec().waitForFinished(); - //Test remove + // Test remove { QTRY_COMPARE(model->rowCount(QModelIndex()), 0); } } - }; QTEST_MAIN(DummyResourceTest) diff --git a/tests/dummyresourcewritebenchmark.cpp b/tests/dummyresourcewritebenchmark.cpp index 539d189..b4ab438 100644 --- a/tests/dummyresourcewritebenchmark.cpp +++ b/tests/dummyresourcewritebenchmark.cpp @@ -123,39 +123,39 @@ class DummyResourceWriteBenchmark : public QObject Q_UNUSED(appendTime); auto bufferSizeTotal = bufferSize * num; - //Wait until all messages have been processed + // Wait until all messages have been processed resource.processAllMessages().exec().waitForFinished(); auto allProcessedTime = time.elapsed(); const auto finalRss = getCurrentRSS(); const auto rssGrowth = finalRss - startingRss; - //Since the database is memory mapped it is attributted to the resident set size. + // Since the database is memory mapped it is attributted to the resident set size. const auto rssWithoutDb = finalRss - DummyResource::diskUsage("org.kde.dummy.instance1"); - const auto peakRss = getPeakRSS(); - //How much peak deviates from final rss in percent - const auto percentageRssError = static_cast(peakRss - finalRss)*100.0/static_cast(finalRss); - auto rssGrowthPerEntity = rssGrowth/num; - std::cout << "Current Rss usage [kb]: " << finalRss/1024 << std::endl; - std::cout << "Peak Rss usage [kb]: " << peakRss/1024 << std::endl; - std::cout << "Rss growth [kb]: " << rssGrowth/1024 << std::endl; + const auto peakRss = getPeakRSS(); + // How much peak deviates from final rss in percent + const auto percentageRssError = static_cast(peakRss - finalRss) * 100.0 / static_cast(finalRss); + auto rssGrowthPerEntity = rssGrowth / num; + std::cout << "Current Rss usage [kb]: " << finalRss / 1024 << std::endl; + std::cout << "Peak Rss usage [kb]: " << peakRss / 1024 << std::endl; + std::cout << "Rss growth [kb]: " << rssGrowth / 1024 << std::endl; std::cout << "Rss growth per entity [byte]: " << rssGrowthPerEntity << std::endl; - std::cout << "Rss without db [kb]: " << rssWithoutDb/1024 << std::endl; + std::cout << "Rss without db [kb]: " << rssWithoutDb / 1024 << std::endl; std::cout << "Percentage peak rss error: " << percentageRssError << std::endl; auto onDisk = DummyResource::diskUsage("org.kde.dummy.instance1"); auto writeAmplification = static_cast(onDisk) / static_cast(bufferSizeTotal); - std::cout << "On disk [kb]: " << onDisk/1024 << std::endl; - std::cout << "Buffer size total [kb]: " << bufferSizeTotal/1024 << std::endl; + std::cout << "On disk [kb]: " << onDisk / 1024 << std::endl; + std::cout << "Buffer size total [kb]: " << bufferSizeTotal / 1024 << std::endl; std::cout << "Write amplification: " << writeAmplification << std::endl; - mTimePerEntity << static_cast(allProcessedTime)/static_cast(num); + mTimePerEntity << static_cast(allProcessedTime) / static_cast(num); mRssGrowthPerEntity << rssGrowthPerEntity; QVERIFY(percentageRssError < 10); - //TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, - //so it doesn't look like that memory is being duplicated. + // TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, + // so it doesn't look like that memory is being duplicated. QVERIFY(rssGrowthPerEntity < 2500); // HAWD::Dataset dataset("dummy_write_in_process", m_hawdState); @@ -219,7 +219,7 @@ private slots: std::system(QString("mdb_stat %1/%2 -ff").arg(Sink::storageLocation()).arg("org.kde.dummy.instance1").toLatin1().constData()); } - //This allows to run individual parts without doing a cleanup, but still cleaning up normally + // This allows to run individual parts without doing a cleanup, but still cleaning up normally void testCleanupForCompleteTest() { DummyResource::removeFromDisk("org.kde.dummy.instance1"); diff --git a/tests/genericfacadetest.cpp b/tests/genericfacadetest.cpp index 397bf6a..8336875 100644 --- a/tests/genericfacadetest.cpp +++ b/tests/genericfacadetest.cpp @@ -9,7 +9,7 @@ #include #include -//Replace with something different +// Replace with something different #include "event_generated.h" @@ -34,7 +34,7 @@ private slots: Sink::Query query; query.liveQuery = false; - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); // storage->mResults << Sink::ApplicationDomain::Event::Ptr::create(); TestResourceFacade facade("identifier", resourceAccess); @@ -44,7 +44,7 @@ private slots: facade.load(query, *resultSet).exec().waitForFinished(); resultSet->initialResultSetComplete(); - //We have to wait for the events that deliver the results to be processed by the eventloop + // We have to wait for the events that deliver the results to be processed by the eventloop result.exec(); QCOMPARE(result.size(), 1); @@ -55,7 +55,7 @@ private slots: Sink::Query query; query.liveQuery = true; - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); // storage->mResults << Sink::ApplicationDomain::Event::Ptr::create(); TestResourceFacade facade("identifier", resourceAccess); @@ -68,13 +68,13 @@ private slots: result.exec(); QCOMPARE(result.size(), 1); - //Enter a second result + // Enter a second result // storage->mResults.clear(); // storage->mResults << QSharedPointer::create("resource", "id2", 0, QSharedPointer()); // storage->mLatestRevision = 2; resourceAccess->emit revisionChanged(2); - //Hack to get event loop in synclistresult to abort again + // Hack to get event loop in synclistresult to abort again resultSet->initialResultSetComplete(); result.exec(); @@ -86,7 +86,7 @@ private slots: Sink::Query query; query.liveQuery = true; - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); auto entity = QSharedPointer::create("resource", "id2", 0, QSharedPointer::create()); entity->setProperty("test", "test1"); @@ -101,7 +101,7 @@ private slots: result.exec(); QCOMPARE(result.size(), 1); - //Modify the entity again + // Modify the entity again // storage->mResults.clear(); entity = QSharedPointer::create("resource", "id2", 0, QSharedPointer::create()); entity->setProperty("test", "test2"); @@ -109,7 +109,7 @@ private slots: // storage->mLatestRevision = 2; resourceAccess->emit revisionChanged(2); - //Hack to get event loop in synclistresult to abort again + // Hack to get event loop in synclistresult to abort again resultSet->initialResultSetComplete(); result.exec(); @@ -122,7 +122,7 @@ private slots: Sink::Query query; query.liveQuery = true; - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); auto entity = QSharedPointer::create("resource", "id2", 0, QSharedPointer()); // storage->mResults << entity; @@ -136,13 +136,13 @@ private slots: result.exec(); QCOMPARE(result.size(), 1); - //Remove the entity again + // Remove the entity again // storage->mResults.clear(); // storage->mRemovals << entity; // storage->mLatestRevision = 2; resourceAccess->emit revisionChanged(2); - //Hack to get event loop in synclistresult to abort again + // Hack to get event loop in synclistresult to abort again resultSet->initialResultSetComplete(); result.exec(); diff --git a/tests/genericresourcebenchmark.cpp b/tests/genericresourcebenchmark.cpp index b3af6a6..a0a368c 100644 --- a/tests/genericresourcebenchmark.cpp +++ b/tests/genericresourcebenchmark.cpp @@ -60,7 +60,8 @@ static QByteArray createEntityBuffer() return QByteArray(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); } -class IndexUpdater : public Sink::Preprocessor { +class IndexUpdater : public Sink::Preprocessor +{ public: void newEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE { @@ -70,7 +71,8 @@ public: } } - void modifiedEntity(const QByteArray &key, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE + void modifiedEntity(const QByteArray &key, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, + Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE { } @@ -117,7 +119,7 @@ private slots: } auto appendTime = time.elapsed(); - //Wait until all messages have been processed + // Wait until all messages have been processed resource.processAllMessages().exec().waitForFinished(); auto allProcessedTime = time.elapsed(); @@ -129,8 +131,8 @@ private slots: HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", num); - row.setValue("append", (qreal)num/appendTime); - row.setValue("total", (qreal)num/allProcessedTime); + row.setValue("append", (qreal)num / appendTime); + row.setValue("total", (qreal)num / allProcessedTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); } @@ -145,7 +147,7 @@ private slots: const QByteArray resourceIdentifier = "org.kde.test.instance1"; auto indexer = QSharedPointer::create(); - pipeline->setPreprocessors("event", QVector() << indexer.data()); + pipeline->setPreprocessors("event", QVector() << indexer.data()); pipeline->setAdaptorFactory("event", eventFactory); TestResource resource("org.kde.test.instance1", pipeline); @@ -160,7 +162,7 @@ private slots: } auto appendTime = time.elapsed(); - //Wait until all messages have been processed + // Wait until all messages have been processed resource.processAllMessages().exec().waitForFinished(); auto allProcessedTime = time.elapsed(); @@ -172,8 +174,8 @@ private slots: HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", num); - row.setValue("append", (qreal)num/appendTime); - row.setValue("total", (qreal)num/allProcessedTime); + row.setValue("append", (qreal)num / appendTime); + row.setValue("total", (qreal)num / allProcessedTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); } @@ -190,7 +192,7 @@ private slots: static flatbuffers::FlatBufferBuilder fbb; fbb.Clear(); - //This is the resource buffer type and not the domain type + // This is the resource buffer type and not the domain type auto type = fbb.CreateString("event"); // auto delta = fbb.CreateVector(entityFbb.GetBufferPointer(), entityFbb.GetSize()); auto delta = Sink::EntityBuffer::appendAsVector(fbb, entityFbb.GetBufferPointer(), entityFbb.GetSize()); diff --git a/tests/genericresourcetest.cpp b/tests/genericresourcetest.cpp index a04c634..7474cbf 100644 --- a/tests/genericresourcetest.cpp +++ b/tests/genericresourcetest.cpp @@ -16,7 +16,7 @@ /** * Test of the generic resource implementation. - * + * * This test relies on a working pipeline implementation, and writes to storage. */ class GenericResourceTest : public QObject @@ -30,7 +30,7 @@ private slots: Sink::Log::setDebugOutputLevel(Sink::Log::Trace); } - ///Ensure the resource can process messages + /// Ensure the resource can process messages void testProcessCommand() { flatbuffers::FlatBufferBuilder eventFbb; @@ -70,7 +70,7 @@ private slots: QVERIFY(Sink::Commands::VerifyCreateEntityBuffer(verifyer)); } - //Actual test + // Actual test auto pipeline = QSharedPointer::create("org.kde.test.instance1"); QSignalSpy revisionSpy(pipeline.data(), SIGNAL(revisionUpdated(qint64))); QVERIFY(revisionSpy.isValid()); diff --git a/tests/getrssusage.cpp b/tests/getrssusage.cpp index 020c7d6..16fec52 100644 --- a/tests/getrssusage.cpp +++ b/tests/getrssusage.cpp @@ -21,7 +21,7 @@ #if defined(__APPLE__) && defined(__MACH__) #include -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) +#elif(defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include #include @@ -40,85 +40,79 @@ * memory use) measured in bytes, or zero if the value cannot be * determined on this OS. */ -size_t getPeakRSS( ) +size_t getPeakRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.PeakWorkingSetSize; - -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) - /* AIX and Solaris ------------------------------------------ */ - struct psinfo psinfo; - int fd = -1; - if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 ) - return (size_t)0L; /* Can't open? */ - if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) ) - { - close( fd ); - return (size_t)0L; /* Can't read? */ - } - close( fd ); - return (size_t)(psinfo.pr_rssize * 1024L); + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.PeakWorkingSetSize; + +#elif(defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) + /* AIX and Solaris ------------------------------------------ */ + struct psinfo psinfo; + int fd = -1; + if ((fd = open("/proc/self/psinfo", O_RDONLY)) == -1) + return (size_t)0L; /* Can't open? */ + if (read(fd, &psinfo, sizeof(psinfo)) != sizeof(psinfo)) { + close(fd); + return (size_t)0L; /* Can't read? */ + } + close(fd); + return (size_t)(psinfo.pr_rssize * 1024L); #elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__APPLE__) && defined(__MACH__)) - /* BSD, Linux, and OSX -------------------------------------- */ - struct rusage rusage; - getrusage( RUSAGE_SELF, &rusage ); + /* BSD, Linux, and OSX -------------------------------------- */ + struct rusage rusage; + getrusage(RUSAGE_SELF, &rusage); #if defined(__APPLE__) && defined(__MACH__) - return (size_t)rusage.ru_maxrss; + return (size_t)rusage.ru_maxrss; #else - return (size_t)(rusage.ru_maxrss * 1024L); + return (size_t)(rusage.ru_maxrss * 1024L); #endif #else - /* Unknown OS ----------------------------------------------- */ - return (size_t)0L; /* Unsupported. */ + /* Unknown OS ----------------------------------------------- */ + return (size_t)0L; /* Unsupported. */ #endif } - - - /** * Returns the current resident set size (physical memory use) measured * in bytes, or zero if the value cannot be determined on this OS. */ -size_t getCurrentRSS( ) +size_t getCurrentRSS() { #if defined(_WIN32) - /* Windows -------------------------------------------------- */ - PROCESS_MEMORY_COUNTERS info; - GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) ); - return (size_t)info.WorkingSetSize; + /* Windows -------------------------------------------------- */ + PROCESS_MEMORY_COUNTERS info; + GetProcessMemoryInfo(GetCurrentProcess(), &info, sizeof(info)); + return (size_t)info.WorkingSetSize; #elif defined(__APPLE__) && defined(__MACH__) - /* OSX ------------------------------------------------------ */ - struct mach_task_basic_info info; - mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; - if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO, - (task_info_t)&info, &infoCount ) != KERN_SUCCESS ) - return (size_t)0L; /* Can't access? */ - return (size_t)info.resident_size; + /* OSX ------------------------------------------------------ */ + struct mach_task_basic_info info; + mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT; + if (task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &infoCount) != KERN_SUCCESS) + return (size_t)0L; /* Can't access? */ + return (size_t)info.resident_size; #elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__) - /* Linux ---------------------------------------------------- */ - long rss = 0L; - FILE* fp = NULL; - if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL ) - return (size_t)0L; /* Can't open? */ - if ( fscanf( fp, "%*s%ld", &rss ) != 1 ) - { - fclose( fp ); - return (size_t)0L; /* Can't read? */ - } - fclose( fp ); - return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE); + /* Linux ---------------------------------------------------- */ + long rss = 0L; + FILE *fp = NULL; + if ((fp = fopen("/proc/self/statm", "r")) == NULL) + return (size_t)0L; /* Can't open? */ + if (fscanf(fp, "%*s%ld", &rss) != 1) { + fclose(fp); + return (size_t)0L; /* Can't read? */ + } + fclose(fp); + return (size_t)rss * (size_t)sysconf(_SC_PAGESIZE); #else - /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ - return (size_t)0L; /* Unsupported. */ + /* AIX, BSD, Solaris, and Unknown OS ------------------------ */ + return (size_t)0L; /* Unsupported. */ #endif } diff --git a/tests/getrssusage.h b/tests/getrssusage.h index e47b14c..bc3d91e 100644 --- a/tests/getrssusage.h +++ b/tests/getrssusage.h @@ -22,7 +22,7 @@ #if defined(__APPLE__) && defined(__MACH__) #include -#elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) +#elif(defined(_AIX) || defined(__TOS__AIX__)) || (defined(__sun__) || defined(__sun) || defined(sun) && (defined(__SVR4) || defined(__svr4__))) #include #include diff --git a/tests/indextest.cpp b/tests/indextest.cpp index 1676ecb..fa3ace4 100644 --- a/tests/indextest.cpp +++ b/tests/indextest.cpp @@ -29,42 +29,29 @@ private slots: void testIndex() { Index index("./testindex", "org.kde.dummy.testindex", Sink::Storage::ReadWrite); - //The first key is specifically a substring of the second key + // The first key is specifically a substring of the second key index.add("key", "value1"); index.add("keyFoo", "value2"); index.add("keyFoo", "value3"); { QList values; - index.lookup(QByteArray("key"), [&values](const QByteArray &value) { - values << value; - }, - [](const Index::Error &error){ qWarning() << "Error: "; }); + index.lookup(QByteArray("key"), [&values](const QByteArray &value) { values << value; }, [](const Index::Error &error) { qWarning() << "Error: "; }); QCOMPARE(values.size(), 1); } { QList values; - index.lookup(QByteArray("keyFoo"), [&values](const QByteArray &value) { - values << value; - }, - [](const Index::Error &error){ qWarning() << "Error: "; }); + index.lookup(QByteArray("keyFoo"), [&values](const QByteArray &value) { values << value; }, [](const Index::Error &error) { qWarning() << "Error: "; }); QCOMPARE(values.size(), 2); } { QList values; - index.lookup(QByteArray("key3"), [&values](const QByteArray &value) { - values << value; - }, - [](const Index::Error &error){ qWarning() << "Error: "; }); + index.lookup(QByteArray("key3"), [&values](const QByteArray &value) { values << value; }, [](const Index::Error &error) { qWarning() << "Error: "; }); QCOMPARE(values.size(), 0); } { QList values; - index.lookup(QByteArray("key"), [&values](const QByteArray &value) { - values << value; - }, - [](const Index::Error &error){ qWarning() << "Error: "; }, - true); + index.lookup(QByteArray("key"), [&values](const QByteArray &value) { values << value; }, [](const Index::Error &error) { qWarning() << "Error: "; }, true); QCOMPARE(values.size(), 3); } } diff --git a/tests/inspectiontest.cpp b/tests/inspectiontest.cpp index cdf62e6..38bf23d 100644 --- a/tests/inspectiontest.cpp +++ b/tests/inspectiontest.cpp @@ -41,7 +41,7 @@ private slots: Mail mail(QByteArray("org.kde.dummy.instance1"), QByteArray("identifier"), 0, QSharedPointer::create()); - //testInspection is a magic property that the dummyresource supports + // testInspection is a magic property that the dummyresource supports auto inspectionCommand = ResourceControl::Inspection::PropertyInspection(mail, "testInspection", success); auto result = ResourceControl::inspect(inspectionCommand).exec(); result.waitForFinished(); diff --git a/tests/maildirresourcetest.cpp b/tests/maildirresourcetest.cpp index d5f7f95..b5c1c3c 100644 --- a/tests/maildirresourcetest.cpp +++ b/tests/maildirresourcetest.cpp @@ -12,8 +12,7 @@ #include "pipeline.h" #include "log.h" -static bool copyRecursively(const QString &srcFilePath, - const QString &tgtFilePath) +static bool copyRecursively(const QString &srcFilePath, const QString &tgtFilePath) { QFileInfo srcFileInfo(srcFilePath); if (srcFileInfo.isDir()) { @@ -26,10 +25,8 @@ static bool copyRecursively(const QString &srcFilePath, 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; + const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName; + const QString newTgtFilePath = tgtFilePath + QLatin1Char('/') + fileName; if (!copyRecursively(newSrcFilePath, newTgtFilePath)) return false; } @@ -44,7 +41,7 @@ static bool copyRecursively(const QString &srcFilePath, /** * Test of complete system using the maildir resource. - * + * * This test requires the maildir resource installed. */ class MaildirResourceTest : public QObject @@ -89,7 +86,7 @@ private slots: Sink::Query query; query.resources << "org.kde.maildir.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -104,7 +101,7 @@ private slots: query.resources << "org.kde.maildir.instance1"; query.parentProperty = "parent"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -121,23 +118,18 @@ private slots: { using namespace Sink; using namespace Sink::ApplicationDomain; - //Ensure all local data is processed + // 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( - Query::ResourceFilter("org.kde.maildir.instance1") + Query::RequestedProperties(QByteArrayList() << "name") - ) - .then, Folder>([](const Folder &folder) { - Trace() << "Found a folder" << folder.identifier(); - return Store::fetchAll( - Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder" << "subject") - ); - }) - .then >([](const QList &mails) { - QVERIFY(mails.size() >= 1); - }) - .exec(); + auto result = Store::fetchOne(Query::ResourceFilter("org.kde.maildir.instance1") + Query::RequestedProperties(QByteArrayList() << "name")) + .then, Folder>([](const Folder &folder) { + Trace() << "Found a folder" << folder.identifier(); + return Store::fetchAll(Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder" + << "subject")); + }) + .then>([](const QList &mails) { QVERIFY(mails.size() >= 1); }) + .exec(); result.waitForFinished(); QVERIFY(!result.errorCode()); } @@ -146,9 +138,12 @@ private slots: { Sink::Query query; query.resources << "org.kde.maildir.instance1"; - query.requestedProperties << "folder" << "subject" << "mimeMessage" << "date"; + query.requestedProperties << "folder" + << "subject" + << "mimeMessage" + << "date"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -171,7 +166,7 @@ private slots: query.resources << "org.kde.maildir.instance1"; query.requestedProperties << "name"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -179,7 +174,7 @@ private slots: QDir dir(targetPath); QVERIFY(dir.rename("inbox", "newbox")); - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -193,13 +188,14 @@ private slots: { Sink::Query query; query.resources << "org.kde.maildir.instance1"; - query.requestedProperties << "folder" << "subject"; + query.requestedProperties << "folder" + << "subject"; - //Ensure all local data is processed + // 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 + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -212,9 +208,10 @@ private slots: { Sink::Query query; query.resources << "org.kde.maildir.instance1"; - query.requestedProperties << "folder" << "subject"; + query.requestedProperties << "folder" + << "subject"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -222,7 +219,7 @@ private slots: QFile file(targetPath); QVERIFY(file.remove()); - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); @@ -236,7 +233,7 @@ private slots: Sink::Query query; query.resources << "org.kde.maildir.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); Sink::ApplicationDomain::Folder folder("org.kde.maildir.instance1"); @@ -244,7 +241,7 @@ private slots: Sink::Store::create(folder).exec().waitForFinished(); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto targetPath = tempDir.path() + "/maildir1/testCreateFolder"; @@ -284,16 +281,16 @@ private slots: Sink::Query query; query.resources << "org.kde.maildir.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); Sink::ApplicationDomain::Mail mail("org.kde.maildir.instance1"); mail.setProperty("name", "testCreateMail"); - //FIXME instead of properties, ensure the mimeMessage property is used and the file is moved as expected + // FIXME instead of properties, ensure the mimeMessage property is used and the file is moved as expected Sink::Store::create(mail).exec().waitForFinished(); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto targetPath = tempDir.path() + "/maildir1/new"; @@ -312,25 +309,23 @@ private slots: ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto result = Store::fetchOne( - Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name") - ) - .then, Folder>([query](const Folder &folder) { - return Store::fetchAll( - Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder" << "subject") - ) - .then, QList >([query](const QList &mails) { - //Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE - if (mails.size() != 1) { - return KAsync::error(1, "Wrong number of mails."); - } - auto mail = mails.first(); - - return Store::remove(*mail) - .then(ResourceControl::flushReplayQueue(query.resources)) //The change needs to be replayed already - .then(ResourceControl::inspect(ResourceControl::Inspection::ExistenceInspection(*mail, false))); - }); - }) - .exec(); + Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name")) + .then, Folder>([query](const Folder &folder) { + return Store::fetchAll(Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder" + << "subject")) + .then, QList>([query](const QList &mails) { + // Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE + if (mails.size() != 1) { + return KAsync::error(1, "Wrong number of mails."); + } + auto mail = mails.first(); + + return Store::remove(*mail) + .then(ResourceControl::flushReplayQueue(query.resources)) // The change needs to be replayed already + .then(ResourceControl::inspect(ResourceControl::Inspection::ExistenceInspection(*mail, false))); + }); + }) + .exec(); result.waitForFinished(); QVERIFY(!result.errorCode()); } @@ -347,61 +342,61 @@ private slots: Folder f; auto result = Store::fetchOne( - Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name") - ) - .then, Folder>([query, &f](const Folder &folder) { - f = folder; - return Store::fetchAll( - Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", folder) + Query::RequestedProperties(QByteArrayList() << "folder" << "subject") - ) - .then, QList >([query](const QList &mails) { - //Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE - if (mails.size() != 1) { - return KAsync::error(1, "Wrong number of mails."); - } - auto mail = mails.first(); - mail->setProperty("unread", true); - return Store::modify(*mail) - .then(ResourceControl::flushReplayQueue(query.resources)) //The change needs to be replayed already - .then(ResourceControl::inspect(ResourceControl::Inspection::PropertyInspection(*mail, "unread", true))) - .then(ResourceControl::inspect(ResourceControl::Inspection::PropertyInspection(*mail, "subject", mail->getProperty("subject")))); - }); - }) - .exec(); + Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("name", "maildir1") + Query::RequestedProperties(QByteArrayList() << "name")) + .then, Folder>([query, &f](const Folder &folder) { + f = folder; + return Store::fetchAll(Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", folder) + + Query::RequestedProperties(QByteArrayList() << "folder" + << "subject")) + .then, QList>([query](const QList &mails) { + // Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE + if (mails.size() != 1) { + return KAsync::error(1, "Wrong number of mails."); + } + auto mail = mails.first(); + mail->setProperty("unread", true); + return Store::modify(*mail) + .then(ResourceControl::flushReplayQueue(query.resources)) // The change needs to be replayed already + .then(ResourceControl::inspect(ResourceControl::Inspection::PropertyInspection(*mail, "unread", true))) + .then(ResourceControl::inspect(ResourceControl::Inspection::PropertyInspection(*mail, "subject", mail->getProperty("subject")))); + }); + }) + .exec(); result.waitForFinished(); QVERIFY(!result.errorCode()); - //Verify that we can still query for all relevant information + // Verify that we can still query for all relevant information auto result2 = Store::fetchAll( - Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", f) + Query::RequestedProperties(QByteArrayList() << "folder" << "subject" << "mimeMessage" << "unread") - ) - .then, QList >([](const QList &mails) { - //Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE - if (mails.size() != 1) { - qWarning() << "Wrong number of mails"; - return KAsync::error(1, "Wrong number of mails."); - } - auto mail = mails.first(); - if (mail->getProperty("subject").toString().isEmpty()) { - qWarning() << "Wrong subject"; - return KAsync::error(1, "Wrong subject."); - } - if (mail->getProperty("unread").toBool() != true) { - qWarning() << "Not unread"; - return KAsync::error(1, "Not unread."); - } - QFileInfo info(mail->getProperty("mimeMessage").toString()); - if (!info.exists()) { - qWarning() << "Wrong subject"; - return KAsync::error(1, "Can't find mime message."); - } - return KAsync::null(); - }) - .exec(); + Query::ResourceFilter("org.kde.maildir.instance1") + Query::PropertyFilter("folder", f) + Query::RequestedProperties(QByteArrayList() << "folder" + << "subject" + << "mimeMessage" + << "unread")) + .then, QList>([](const QList &mails) { + // Can't use QCOMPARE because it tries to return FIXME Implement ASYNCCOMPARE + if (mails.size() != 1) { + qWarning() << "Wrong number of mails"; + return KAsync::error(1, "Wrong number of mails."); + } + auto mail = mails.first(); + if (mail->getProperty("subject").toString().isEmpty()) { + qWarning() << "Wrong subject"; + return KAsync::error(1, "Wrong subject."); + } + if (mail->getProperty("unread").toBool() != true) { + qWarning() << "Not unread"; + return KAsync::error(1, "Not unread."); + } + QFileInfo info(mail->getProperty("mimeMessage").toString()); + if (!info.exists()) { + qWarning() << "Wrong subject"; + return KAsync::error(1, "Can't find mime message."); + } + return KAsync::null(); + }) + .exec(); result2.waitForFinished(); QVERIFY(!result2.errorCode()); } - }; QTEST_MAIN(MaildirResourceTest) diff --git a/tests/maildirsyncbenchmark.cpp b/tests/maildirsyncbenchmark.cpp index 7904a82..06c5ab1 100644 --- a/tests/maildirsyncbenchmark.cpp +++ b/tests/maildirsyncbenchmark.cpp @@ -16,8 +16,7 @@ #include "log.h" -static bool copyRecursively(const QString &srcFilePath, - const QString &tgtFilePath) +static bool copyRecursively(const QString &srcFilePath, const QString &tgtFilePath) { QFileInfo srcFileInfo(srcFilePath); if (srcFileInfo.isDir()) { @@ -30,10 +29,8 @@ static bool copyRecursively(const QString &srcFilePath, 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; + const QString newSrcFilePath = srcFilePath + QLatin1Char('/') + fileName; + const QString newTgtFilePath = tgtFilePath + QLatin1Char('/') + fileName; if (!copyRecursively(newSrcFilePath, newTgtFilePath)) return false; } @@ -48,7 +45,7 @@ static bool copyRecursively(const QString &srcFilePath, /** * Test of complete system using the maildir resource. - * + * * This test requires the maildir resource installed. */ class MaildirSyncBenchmark : public QObject @@ -102,7 +99,6 @@ private slots: // row.setValue("totalTime", allProcessedTime); // dataset.insertRow(row); // HAWD::Formatter::print(dataset); - } }; diff --git a/tests/mailquerybenchmark.cpp b/tests/mailquerybenchmark.cpp index ea919ac..6b93863 100644 --- a/tests/mailquerybenchmark.cpp +++ b/tests/mailquerybenchmark.cpp @@ -61,9 +61,9 @@ class MailQueryBenchmark : public QObject auto pipeline = QSharedPointer::create(resourceIdentifier); auto mailFactory = QSharedPointer::create(); - auto indexer = QSharedPointer >::create(); + auto indexer = QSharedPointer>::create(); - pipeline->setPreprocessors("mail", QVector() << indexer.data()); + pipeline->setPreprocessors("mail", QVector() << indexer.data()); pipeline->setAdaptorFactory("mail", mailFactory); auto domainTypeAdaptorFactory = QSharedPointer::create(); @@ -88,11 +88,11 @@ class MailQueryBenchmark : public QObject const auto startingRss = getCurrentRSS(); - //Benchmark + // Benchmark QTime time; time.start(); - auto resultSet = QSharedPointer >::create(); + auto resultSet = QSharedPointer>::create(); auto resourceAccess = QSharedPointer::create(); TestMailResourceFacade facade(resourceIdentifier, resourceAccess); @@ -100,13 +100,9 @@ class MailQueryBenchmark : public QObject ret.first.exec().waitForFinished(); auto emitter = ret.second; QList list; - emitter->onAdded([&list](const Sink::ApplicationDomain::Mail::Ptr &mail) { - list << mail; - }); + emitter->onAdded([&list](const Sink::ApplicationDomain::Mail::Ptr &mail) { list << mail; }); bool done = false; - emitter->onInitialResultSetComplete([&done](const Sink::ApplicationDomain::Mail::Ptr &mail) { - done = true; - }); + emitter->onInitialResultSetComplete([&done](const Sink::ApplicationDomain::Mail::Ptr &mail) { done = true; }); emitter->fetch(Sink::ApplicationDomain::Mail::Ptr()); QTRY_VERIFY(done); QCOMPARE(list.size(), query.limit); @@ -115,32 +111,32 @@ class MailQueryBenchmark : public QObject const auto finalRss = getCurrentRSS(); const auto rssGrowth = finalRss - startingRss; - //Since the database is memory mapped it is attributted to the resident set size. + // Since the database is memory mapped it is attributted to the resident set size. const auto rssWithoutDb = finalRss - Sink::Storage(Sink::storageLocation(), resourceIdentifier, Sink::Storage::ReadWrite).diskUsage(); - const auto peakRss = getPeakRSS(); - //How much peak deviates from final rss in percent (should be around 0) - const auto percentageRssError = static_cast(peakRss - finalRss)*100.0/static_cast(finalRss); - auto rssGrowthPerEntity = rssGrowth/count; + const auto peakRss = getPeakRSS(); + // How much peak deviates from final rss in percent (should be around 0) + const auto percentageRssError = static_cast(peakRss - finalRss) * 100.0 / static_cast(finalRss); + auto rssGrowthPerEntity = rssGrowth / count; std::cout << "Loaded " << list.size() << " results." << std::endl; std::cout << "The query took [ms]: " << elapsed << std::endl; - std::cout << "Current Rss usage [kb]: " << finalRss/1024 << std::endl; - std::cout << "Peak Rss usage [kb]: " << peakRss/1024 << std::endl; - std::cout << "Rss growth [kb]: " << rssGrowth/1024 << std::endl; + std::cout << "Current Rss usage [kb]: " << finalRss / 1024 << std::endl; + std::cout << "Peak Rss usage [kb]: " << peakRss / 1024 << std::endl; + std::cout << "Rss growth [kb]: " << rssGrowth / 1024 << std::endl; std::cout << "Rss growth per entity [byte]: " << rssGrowthPerEntity << std::endl; - std::cout << "Rss without db [kb]: " << rssWithoutDb/1024 << std::endl; + std::cout << "Rss without db [kb]: " << rssWithoutDb / 1024 << std::endl; std::cout << "Percentage error: " << percentageRssError << std::endl; HAWD::Dataset dataset("mail_query", mHawdState); HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", list.size()); - row.setValue("queryResultPerMs", (qreal)list.size()/elapsed); + row.setValue("queryResultPerMs", (qreal)list.size() / elapsed); dataset.insertRow(row); HAWD::Formatter::print(dataset); QVERIFY(percentageRssError < 10); - //TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, - //so it doesn't look like that memory is being duplicated. + // TODO This is much more than it should it seems, although adding the attachment results in pretty exactly a 1k increase, + // so it doesn't look like that memory is being duplicated. QVERIFY(rssGrowthPerEntity < 3300); // Print memory layout, RSS is what is in memory @@ -159,7 +155,9 @@ private slots: { Sink::Query query; query.liveQuery = false; - query.requestedProperties << "uid" << "subject" << "date"; + query.requestedProperties << "uid" + << "subject" + << "date"; query.sortProperty = "date"; query.propertyFilter.insert("folder", "folder1"); query.limit = 1000; @@ -167,7 +165,6 @@ private slots: populateDatabase(50000); testLoad(query, 50000); } - }; QTEST_MAIN(MailQueryBenchmark) diff --git a/tests/messagequeuetest.cpp b/tests/messagequeuetest.cpp index 06a4ae6..484ff86 100644 --- a/tests/messagequeuetest.cpp +++ b/tests/messagequeuetest.cpp @@ -45,12 +45,7 @@ private slots: MessageQueue queue(Sink::Store::storageLocation(), "org.kde.dummy.testqueue"); bool gotValue = false; bool gotError = false; - queue.dequeue([&](void *ptr, int size, std::function callback) { - gotValue = true; - }, - [&](const MessageQueue::Error &error) { - gotError = true; - }); + queue.dequeue([&](void *ptr, int size, std::function callback) { gotValue = true; }, [&](const MessageQueue::Error &error) { gotError = true; }); QVERIFY(!gotValue); QVERIFY(!gotError); } @@ -69,9 +64,7 @@ private slots: QSignalSpy spy(&queue, SIGNAL(drained())); queue.enqueue("value1"); - queue.dequeue([](void *ptr, int size, std::function callback) { - callback(true); - }, [](const MessageQueue::Error &error) {}); + queue.dequeue([](void *ptr, int size, std::function callback) { callback(true); }, [](const MessageQueue::Error &error) {}); QCOMPARE(spy.size(), 1); } @@ -91,15 +84,14 @@ private slots: const auto expected = values.dequeue(); bool gotValue = false; bool gotError = false; - queue.dequeue([&](void *ptr, int size, std::function callback) { - if (QByteArray(static_cast(ptr), size) == expected) { - gotValue = true; - } - callback(true); - }, - [&](const MessageQueue::Error &error) { - gotError = true; - }); + queue.dequeue( + [&](void *ptr, int size, std::function callback) { + if (QByteArray(static_cast(ptr), size) == expected) { + gotValue = true; + } + callback(true); + }, + [&](const MessageQueue::Error &error) { gotError = true; }); QVERIFY(gotValue); QVERIFY(!gotError); } @@ -123,22 +115,21 @@ private slots: bool gotValue = false; bool gotError = false; - queue.dequeue([&](void *ptr, int size, std::function callback) { - if (QByteArray(static_cast(ptr), size) == expected) { - gotValue = true; - } - auto timer = new QTimer(); - timer->setSingleShot(true); - QObject::connect(timer, &QTimer::timeout, [timer, callback, &eventLoop]() { - delete timer; - callback(true); - eventLoop.exit(); - }); - timer->start(0); - }, - [&](const MessageQueue::Error &error) { - gotError = true; - }); + queue.dequeue( + [&](void *ptr, int size, std::function callback) { + if (QByteArray(static_cast(ptr), size) == expected) { + gotValue = true; + } + auto timer = new QTimer(); + timer->setSingleShot(true); + QObject::connect(timer, &QTimer::timeout, [timer, callback, &eventLoop]() { + delete timer; + callback(true); + eventLoop.exit(); + }); + timer->start(0); + }, + [&](const MessageQueue::Error &error) { gotError = true; }); eventLoop.exec(); QVERIFY(gotValue); QVERIFY(!gotError); @@ -155,13 +146,12 @@ private slots: queue.enqueue("value1"); bool gotError = false; - queue.dequeue([&](void *ptr, int size, std::function callback) { - queue.enqueue("value3"); - callback(true); - }, - [&](const MessageQueue::Error &error) { - gotError = true; - }); + queue.dequeue( + [&](void *ptr, int size, std::function callback) { + queue.enqueue("value3"); + callback(true); + }, + [&](const MessageQueue::Error &error) { gotError = true; }); QVERIFY(!gotError); } @@ -174,15 +164,15 @@ private slots: int count = 0; queue.dequeueBatch(2, [&count](const QByteArray &data) { - count++; - return KAsync::null(); - }).exec().waitForFinished(); + count++; + return KAsync::null(); + }).exec().waitForFinished(); QCOMPARE(count, 2); queue.dequeueBatch(1, [&count](const QByteArray &data) { - count++; - return KAsync::null(); - }).exec().waitForFinished(); + count++; + return KAsync::null(); + }).exec().waitForFinished(); QCOMPARE(count, 3); } @@ -203,7 +193,6 @@ private slots: QVERIFY(!queue.isEmpty()); QCOMPARE(spy.count(), 1); } - }; QTEST_MAIN(MessageQueueTest) diff --git a/tests/modelinteractivitytest.cpp b/tests/modelinteractivitytest.cpp index ad23e0f..d0a0920 100644 --- a/tests/modelinteractivitytest.cpp +++ b/tests/modelinteractivitytest.cpp @@ -16,20 +16,23 @@ static int blockingTime; class TimeMeasuringApplication : public QCoreApplication { QElapsedTimer t; + public: - TimeMeasuringApplication(int& argc, char ** argv) : QCoreApplication(argc, argv) { } - virtual ~TimeMeasuringApplication() { } + TimeMeasuringApplication(int &argc, char **argv) : QCoreApplication(argc, argv) + { + } + virtual ~TimeMeasuringApplication() + { + } - virtual bool notify(QObject* receiver, QEvent* event) + virtual bool notify(QObject *receiver, QEvent *event) { t.start(); const bool ret = QCoreApplication::notify(receiver, event); - if(t.elapsed() > 1) - std::cout << QString("processing event type %1 for object %2 took %3ms") - .arg((int)event->type()) - .arg(""/* receiver->objectName().toLocal8Bit().data()*/) - .arg((int)t.elapsed()) - .toStdString() << std::endl; + if (t.elapsed() > 1) + std::cout + << QString("processing event type %1 for object %2 took %3ms").arg((int)event->type()).arg("" /* receiver->objectName().toLocal8Bit().data()*/).arg((int)t.elapsed()).toStdString() + << std::endl; blockingTime += t.elapsed(); return ret; } @@ -62,7 +65,7 @@ private slots: void testSingle() { - //Setup + // Setup { Sink::ApplicationDomain::Mail mail("org.kde.dummy.instance1"); for (int i = 0; i < 1000; i++) { @@ -76,13 +79,13 @@ private slots: Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //Test + // Test QTime time; time.start(); auto model = Sink::Store::loadModel(query); blockingTime += time.elapsed(); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); - //Never block longer than 10 ms + // Never block longer than 10 ms QVERIFY2(blockingTime < 10, QString("Total blocking time: %1").arg(blockingTime).toLatin1().data()); } }; diff --git a/tests/pipelinebenchmark.cpp b/tests/pipelinebenchmark.cpp index 5743830..0133a6c 100644 --- a/tests/pipelinebenchmark.cpp +++ b/tests/pipelinebenchmark.cpp @@ -54,7 +54,8 @@ // } // } // -// void modifiedEntity(const QByteArray &key, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE +// void modifiedEntity(const QByteArray &key, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, +// Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE // { // } // @@ -66,7 +67,7 @@ /** * Benchmark pipeline processing speed. - * + * * This benchmark especially highlights: * * Cost of an index in speed and size */ @@ -77,7 +78,7 @@ class PipelineBenchmark : public QObject QByteArray resourceIdentifier; HAWD::State mHawdState; - void populateDatabase(int count, const QVector &preprocessors) + void populateDatabase(int count, const QVector &preprocessors) { TestResource::removeFromDisk(resourceIdentifier); @@ -112,18 +113,17 @@ class PipelineBenchmark : public QObject // Print memory layout, RSS is what is in memory // std::system("exec pmap -x \"$PPID\""); // - std::cout << "Size: " << Sink::Storage(Sink::storageLocation(), resourceIdentifier, Sink::Storage::ReadOnly).diskUsage()/1024 << " [kb]" << std::endl; + std::cout << "Size: " << Sink::Storage(Sink::storageLocation(), resourceIdentifier, Sink::Storage::ReadOnly).diskUsage() / 1024 << " [kb]" << std::endl; std::cout << "Time: " << allProcessedTime << " [ms]" << std::endl; HAWD::Dataset dataset("pipeline", mHawdState); HAWD::Dataset::Row row = dataset.row(); row.setValue("rows", count); - row.setValue("append", (qreal)count/appendTime); - row.setValue("total", (qreal)count/allProcessedTime); + row.setValue("append", (qreal)count / appendTime); + row.setValue("total", (qreal)count / allProcessedTime); dataset.insertRow(row); HAWD::Formatter::print(dataset); - } private slots: @@ -136,15 +136,14 @@ private slots: void testWithoutIndex() { - populateDatabase(10000, QVector()); + populateDatabase(10000, QVector()); } void testWithIndex() { - auto indexer = QSharedPointer >::create(); - populateDatabase(10000, QVector() << indexer.data()); + auto indexer = QSharedPointer>::create(); + populateDatabase(10000, QVector() << indexer.data()); } - }; QTEST_MAIN(PipelineBenchmark) diff --git a/tests/pipelinetest.cpp b/tests/pipelinetest.cpp index 92b7554..cdd260d 100644 --- a/tests/pipelinetest.cpp +++ b/tests/pipelinetest.cpp @@ -143,7 +143,8 @@ QByteArray deleteEntityCommand(const QByteArray &uid, qint64 revision) return command; } -class TestProcessor : public Sink::Preprocessor { +class TestProcessor : public Sink::Preprocessor +{ public: void newEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE { @@ -151,7 +152,8 @@ public: newRevisions << revision; } - void modifiedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE + void modifiedEntity(const QByteArray &uid, qint64 revision, const Sink::ApplicationDomain::BufferAdaptor &oldEntity, const Sink::ApplicationDomain::BufferAdaptor &newEntity, + Sink::Storage::Transaction &transaction) Q_DECL_OVERRIDE { modifiedUids << uid; modifiedRevisions << revision; @@ -214,42 +216,42 @@ private slots: auto adaptorFactory = QSharedPointer::create(); pipeline.setAdaptorFactory("event", adaptorFactory); - //Create the initial revision + // Create the initial revision pipeline.startTransaction(); pipeline.newEntity(command.constData(), command.size()); pipeline.commit(); - //Get uid of written entity + // Get uid of written entity auto keys = getKeys("org.kde.pipelinetest.instance1", "event.main"); QCOMPARE(keys.size(), 1); const auto key = keys.first(); const auto uid = Sink::Storage::uidFromKey(key); - //Execute the modification + // Execute the modification entityFbb.Clear(); auto modifyCommand = modifyEntityCommand(createEvent(entityFbb, "summary2"), uid, 1); pipeline.startTransaction(); pipeline.modifiedEntity(modifyCommand.constData(), modifyCommand.size()); pipeline.commit(); - //Ensure we've got the new revision with the modification + // Ensure we've got the new revision with the modification auto buffer = getEntity("org.kde.pipelinetest.instance1", "event.main", Sink::Storage::assembleKey(uid, 2)); QVERIFY(!buffer.isEmpty()); Sink::EntityBuffer entityBuffer(buffer.data(), buffer.size()); auto adaptor = adaptorFactory->createAdaptor(entityBuffer.entity()); QVERIFY2(adaptor->getProperty("summary").toString() == QString("summary2"), "The modification isn't applied."); - //Ensure we didn't modify anything else + // Ensure we didn't modify anything else QVERIFY2(adaptor->getProperty("description").toString() == QString("description"), "The modification has sideeffects."); - //Both revisions are in the store at this point + // Both revisions are in the store at this point QCOMPARE(getKeys("org.kde.pipelinetest.instance1", "event.main").size(), 2); - //Cleanup old revisions + // Cleanup old revisions pipeline.startTransaction(); pipeline.cleanupRevision(2); pipeline.commit(); - //And now only the latest revision is left + // And now only the latest revision is left QCOMPARE(getKeys("org.kde.pipelinetest.instance1", "event.main").size(), 1); } @@ -263,18 +265,18 @@ private slots: auto adaptorFactory = QSharedPointer::create(); pipeline.setAdaptorFactory("event", adaptorFactory); - //Create the initial revision + // Create the initial revision pipeline.startTransaction(); pipeline.newEntity(command.constData(), command.size()); pipeline.commit(); - //Get uid of written entity + // Get uid of written entity auto keys = getKeys("org.kde.pipelinetest.instance1", "event.main"); QCOMPARE(keys.size(), 1); const auto uid = Sink::Storage::uidFromKey(keys.first()); - //Create another operation inbetween + // Create another operation inbetween { entityFbb.Clear(); auto command = createEntityCommand(createEvent(entityFbb)); @@ -283,14 +285,14 @@ private slots: pipeline.commit(); } - //Execute the modification on revision 2 + // Execute the modification on revision 2 entityFbb.Clear(); auto modifyCommand = modifyEntityCommand(createEvent(entityFbb, "summary2"), uid, 2); pipeline.startTransaction(); pipeline.modifiedEntity(modifyCommand.constData(), modifyCommand.size()); pipeline.commit(); - //Ensure we've got the new revision with the modification + // Ensure we've got the new revision with the modification auto buffer = getEntity("org.kde.pipelinetest.instance1", "event.main", Sink::Storage::assembleKey(uid, 3)); QVERIFY(!buffer.isEmpty()); Sink::EntityBuffer entityBuffer(buffer.data(), buffer.size()); @@ -305,7 +307,7 @@ private slots: Sink::Pipeline pipeline("org.kde.pipelinetest.instance1"); pipeline.setAdaptorFactory("event", QSharedPointer::create()); - //Create the initial revision + // Create the initial revision pipeline.startTransaction(); pipeline.newEntity(command.constData(), command.size()); pipeline.commit(); @@ -315,21 +317,21 @@ private slots: const auto uid = Sink::Storage::uidFromKey(result.first()); - //Delete entity + // Delete entity auto deleteCommand = deleteEntityCommand(uid, 1); pipeline.startTransaction(); pipeline.deletedEntity(deleteCommand.constData(), deleteCommand.size()); pipeline.commit(); - //We have a new revision that indicates the deletion + // We have a new revision that indicates the deletion QCOMPARE(getKeys("org.kde.pipelinetest.instance1", "event.main").size(), 2); - //Cleanup old revisions + // Cleanup old revisions pipeline.startTransaction(); pipeline.cleanupRevision(2); pipeline.commit(); - //And all revisions are gone + // And all revisions are gone QCOMPARE(getKeys("org.kde.pipelinetest.instance1", "event.main").size(), 0); } @@ -340,17 +342,17 @@ private slots: TestProcessor testProcessor; Sink::Pipeline pipeline("org.kde.pipelinetest.instance1"); - pipeline.setPreprocessors("event", QVector() << &testProcessor); + pipeline.setPreprocessors("event", QVector() << &testProcessor); pipeline.startTransaction(); pipeline.setAdaptorFactory("event", QSharedPointer::create()); - //Actual test + // Actual test { auto command = createEntityCommand(createEvent(entityFbb)); pipeline.newEntity(command.constData(), command.size()); QCOMPARE(testProcessor.newUids.size(), 1); QCOMPARE(testProcessor.newRevisions.size(), 1); - //Key doesn't contain revision and is just the uid + // Key doesn't contain revision and is just the uid QCOMPARE(testProcessor.newUids.at(0), Sink::Storage::uidFromKey(testProcessor.newUids.at(0))); } pipeline.commit(); @@ -364,7 +366,7 @@ private slots: pipeline.modifiedEntity(modifyCommand.constData(), modifyCommand.size()); QCOMPARE(testProcessor.modifiedUids.size(), 1); QCOMPARE(testProcessor.modifiedRevisions.size(), 1); - //Key doesn't contain revision and is just the uid + // Key doesn't contain revision and is just the uid QCOMPARE(testProcessor.modifiedUids.at(0), Sink::Storage::uidFromKey(testProcessor.modifiedUids.at(0))); } pipeline.commit(); @@ -376,7 +378,7 @@ private slots: QCOMPARE(testProcessor.deletedUids.size(), 1); QCOMPARE(testProcessor.deletedUids.size(), 1); QCOMPARE(testProcessor.deletedSummaries.size(), 1); - //Key doesn't contain revision and is just the uid + // Key doesn't contain revision and is just the uid QCOMPARE(testProcessor.deletedUids.at(0), Sink::Storage::uidFromKey(testProcessor.deletedUids.at(0))); QCOMPARE(testProcessor.deletedSummaries.at(0), QByteArray("summary2")); } diff --git a/tests/querytest.cpp b/tests/querytest.cpp index 2531c25..7b9129e 100644 --- a/tests/querytest.cpp +++ b/tests/querytest.cpp @@ -42,12 +42,12 @@ private slots: void testNoResources() { - //Test + // Test Sink::Query query; query.resources << "foobar"; query.liveQuery = true; - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(), 0); @@ -56,39 +56,39 @@ private slots: void testSingle() { - //Setup + // Setup { Sink::ApplicationDomain::Mail mail("org.kde.dummy.instance1"); Sink::Store::create(mail).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.liveQuery = true; - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_COMPARE(model->rowCount(), 1); } void testSingleWithDelay() { - //Setup + // Setup { Sink::ApplicationDomain::Mail mail("org.kde.dummy.instance1"); Sink::Store::create(mail).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.liveQuery = false; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //We fetch after the data is available and don't rely on the live query mechanism to deliver the actual data + // We fetch after the data is available and don't rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); @@ -98,7 +98,7 @@ private slots: void testById() { QByteArray id; - //Setup + // Setup { Sink::ApplicationDomain::Mail mail("org.kde.dummy.instance1"); Sink::Store::create(mail).exec().waitForFinished(); @@ -107,17 +107,17 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::Store::synchronize(query).exec().waitForFinished(); - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QVERIFY(model->rowCount() >= 1); id = model->index(0, 0).data(Sink::Store::DomainObjectRole).value()->identifier(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.ids << id; @@ -128,18 +128,18 @@ private slots: void testFolder() { - //Setup + // Setup { Sink::ApplicationDomain::Folder folder("org.kde.dummy.instance1"); Sink::Store::create(folder).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.liveQuery = true; - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_COMPARE(model->rowCount(), 1); auto folderEntity = model->index(0, 0).data(Sink::Store::DomainObjectRole).value(); @@ -148,7 +148,7 @@ private slots: void testFolderTree() { - //Setup + // Setup { Sink::ApplicationDomain::Folder folder("org.kde.dummy.instance1"); Sink::Store::create(folder).exec().waitForFinished(); @@ -156,7 +156,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto model = Sink::Store::loadModel(query); @@ -171,15 +171,15 @@ private slots: Sink::Store::create(subfolder).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.parentProperty = "parent"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //We fetch after the data is available and don't rely on the live query mechanism to deliver the actual data + // We fetch after the data is available and don't rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(), 1); @@ -190,7 +190,7 @@ private slots: void testMailByUid() { - //Setup + // Setup { Sink::ApplicationDomain::Mail mail("org.kde.dummy.instance1"); mail.setProperty("uid", "test1"); @@ -198,16 +198,16 @@ private slots: Sink::Store::create(mail).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.liveQuery = false; query.propertyFilter.insert("uid", "test1"); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(), 1); @@ -215,7 +215,7 @@ private slots: void testMailByFolder() { - //Setup + // Setup Sink::ApplicationDomain::Folder::Ptr folderEntity; { Sink::ApplicationDomain::Folder folder("org.kde.dummy.instance1"); @@ -224,7 +224,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto model = Sink::Store::loadModel(query); @@ -240,15 +240,15 @@ private slots: Sink::Store::create(mail).exec().waitForFinished(); } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.propertyFilter.insert("folder", folderEntity->identifier()); - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); - //We fetch before the data is available and rely on the live query mechanism to deliver the actual data + // We fetch before the data is available and rely on the live query mechanism to deliver the actual data auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(), 1); @@ -256,7 +256,7 @@ private slots: void testMailByFolderSortedByDate() { - //Setup + // Setup Sink::ApplicationDomain::Folder::Ptr folderEntity; { Sink::ApplicationDomain::Folder folder("org.kde.dummy.instance1"); @@ -265,7 +265,7 @@ private slots: Sink::Query query; query.resources << "org.kde.dummy.instance1"; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto model = Sink::Store::loadModel(query); @@ -299,7 +299,7 @@ private slots: } } - //Test + // Test Sink::Query query; query.resources << "org.kde.dummy.instance1"; query.propertyFilter.insert("folder", folderEntity->identifier()); @@ -307,19 +307,19 @@ private slots: query.limit = 1; query.liveQuery = false; - //Ensure all local data is processed + // Ensure all local data is processed Sink::ResourceControl::flushMessageQueue(query.resources).exec().waitForFinished(); auto model = Sink::Store::loadModel(query); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); - //The model is not sorted, but the limited set is sorted, so we can only test for the latest result. + // The model is not sorted, but the limited set is sorted, so we can only test for the latest result. QCOMPARE(model->rowCount(), 1); QCOMPARE(model->index(0, 0).data(Sink::Store::DomainObjectRole).value()->getProperty("uid").toByteArray(), QByteArray("testLatest")); model->fetchMore(QModelIndex()); QTRY_VERIFY(model->data(QModelIndex(), Sink::Store::ChildrenFetchedRole).toBool()); QCOMPARE(model->rowCount(), 2); - //We can't make any assumptions about the order of the indexes + // We can't make any assumptions about the order of the indexes // QCOMPARE(model->index(1, 0).data(Sink::Store::DomainObjectRole).value()->getProperty("uid").toByteArray(), QByteArray("testSecond")); } }; diff --git a/tests/resourcecommunicationtest.cpp b/tests/resourcecommunicationtest.cpp index db8703e..2daf372 100644 --- a/tests/resourcecommunicationtest.cpp +++ b/tests/resourcecommunicationtest.cpp @@ -51,14 +51,13 @@ private slots: int errors = 0; for (int i = 0; i < count; i++) { auto result = resourceAccess.sendCommand(Sink::Commands::PingCommand) - .then([&complete]() { - complete++; - }, - [&errors, &complete](int error, const QString &msg) { - qWarning() << msg; - errors++; - complete++; - }).exec(); + .then([&complete]() { complete++; }, + [&errors, &complete](int error, const QString &msg) { + qWarning() << msg; + errors++; + complete++; + }) + .exec(); } QTRY_COMPARE(complete, count); QVERIFY(!errors); @@ -77,17 +76,18 @@ private slots: int errors = 0; for (int i = 0; i < count; i++) { resourceAccess.sendCommand(Sink::Commands::PingCommand) - .then([&complete]() { - complete++; - }, - [&errors, &complete](int error, const QString &msg) { - qWarning() << msg; - errors++; - complete++; - }).then([&resourceAccess]() { + .then([&complete]() { complete++; }, + [&errors, &complete](int error, const QString &msg) { + qWarning() << msg; + errors++; + complete++; + }) + .then([&resourceAccess]() { resourceAccess.close(); resourceAccess.open(); - }).exec().waitForFinished(); + }) + .exec() + .waitForFinished(); } QTRY_COMPARE(complete, count); QVERIFY(!errors); diff --git a/tests/storagebenchmark.cpp b/tests/storagebenchmark.cpp index 8498df9..a1ddcc9 100644 --- a/tests/storagebenchmark.cpp +++ b/tests/storagebenchmark.cpp @@ -18,7 +18,7 @@ using namespace flatbuffers; static QByteArray createEvent() { - static const size_t attachmentSize = 1024*2; // 2KB + static const size_t attachmentSize = 1024 * 2; // 2KB static uint8_t rawData[attachmentSize]; static FlatBufferBuilder fbb; fbb.Clear(); @@ -26,13 +26,13 @@ static QByteArray createEvent() uint8_t *rawDataPtr = Q_NULLPTR; auto summary = fbb.CreateString("summary"); auto data = fbb.CreateUninitializedVector(attachmentSize, &rawDataPtr); - //auto data = fbb.CreateVector(rawData, attachmentSize); + // auto data = fbb.CreateVector(rawData, attachmentSize); Calendar::EventBuilder eventBuilder(fbb); eventBuilder.add_summary(summary); eventBuilder.add_attachment(data); auto eventLocation = eventBuilder.Finish(); Calendar::FinishEventBuffer(fbb, eventLocation); - memcpy((void*)rawDataPtr, rawData, attachmentSize); + memcpy((void *)rawDataPtr, rawData, attachmentSize); } return QByteArray::fromRawData(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); @@ -45,7 +45,7 @@ class StorageBenchmark : public QObject { Q_OBJECT private: - //This should point to a directory on disk and not a ramdisk (since we're measuring performance) + // This should point to a directory on disk and not a ramdisk (since we're measuring performance) QString testDataPath; QString dbName; QString filePath; @@ -76,7 +76,7 @@ private slots: QTime time; time.start(); - //Test db write time + // Test db write time { auto transaction = store->createTransaction(Sink::Storage::ReadWrite); for (int i = 0; i < count; i++) { @@ -91,7 +91,7 @@ private slots: qreal dbWriteDuration = time.restart(); qreal dbWriteOpsPerMs = count / dbWriteDuration; - //Test file write time + // Test file write time { std::ofstream myfile; myfile.open(filePath.toStdString()); @@ -103,7 +103,7 @@ private slots: qreal fileWriteDuration = time.restart(); qreal fileWriteOpsPerMs = count / fileWriteDuration; - //Db read time + // Db read time { auto transaction = store->createTransaction(Sink::Storage::ReadOnly); auto db = transaction.openDatabase(); @@ -127,10 +127,10 @@ private slots: void testSizes() { Sink::Storage store(testDataPath, dbName); - qDebug() << "Database size [kb]: " << store.diskUsage()/1024; + qDebug() << "Database size [kb]: " << store.diskUsage() / 1024; QFileInfo fileInfo(filePath); - qDebug() << "File size [kb]: " << fileInfo.size()/1024; + qDebug() << "File size [kb]: " << fileInfo.size() / 1024; } void testScan() @@ -139,13 +139,15 @@ private slots: QBENCHMARK { int hit = 0; - store->createTransaction(Sink::Storage::ReadOnly).openDatabase().scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { - if (key == "key10000") { - //qDebug() << "hit"; - hit++; - } - return true; - }); + store->createTransaction(Sink::Storage::ReadOnly) + .openDatabase() + .scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { + if (key == "key10000") { + // qDebug() << "hit"; + hit++; + } + return true; + }); QCOMPARE(hit, 1); } } diff --git a/tests/storagetest.cpp b/tests/storagetest.cpp index ebd9b8f..31809ce 100644 --- a/tests/storagetest.cpp +++ b/tests/storagetest.cpp @@ -24,7 +24,7 @@ private: Sink::Storage storage(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = storage.createTransaction(Sink::Storage::ReadWrite); for (int i = 0; i < count; i++) { - //This should perhaps become an implementation detail of the db? + // This should perhaps become an implementation detail of the db? if (i % 10000 == 0) { if (i > 0) { transaction.commit(); @@ -41,19 +41,20 @@ private: bool success = true; bool keyMatch = true; const auto reference = keyPrefix + QByteArray::number(i); - storage.createTransaction(Sink::Storage::ReadOnly).openDatabase().scan(keyPrefix + QByteArray::number(i), - [&keyMatch, &reference](const QByteArray &key, const QByteArray &value) -> bool { - if (value != reference) { - qDebug() << "Mismatch while reading"; - keyMatch = false; - } - return keyMatch; - }, - [&success](const Sink::Storage::Error &error) { - qDebug() << error.message; - success = false; - } - ); + storage.createTransaction(Sink::Storage::ReadOnly) + .openDatabase() + .scan(keyPrefix + QByteArray::number(i), + [&keyMatch, &reference](const QByteArray &key, const QByteArray &value) -> bool { + if (value != reference) { + qDebug() << "Mismatch while reading"; + keyMatch = false; + } + return keyMatch; + }, + [&success](const Sink::Storage::Error &error) { + qDebug() << error.message; + success = false; + }); return success && keyMatch; } @@ -87,7 +88,7 @@ private slots: populate(count); - //ensure we can read everything back correctly + // ensure we can read everything back correctly { Sink::Storage storage(testDataPath, dbName); for (int i = 0; i < count; i++) { @@ -101,31 +102,35 @@ private slots: const int count = 100; populate(count); - //ensure we can scan for values + // ensure we can scan for values { int hit = 0; Sink::Storage store(testDataPath, dbName); - store.createTransaction(Sink::Storage::ReadOnly).openDatabase().scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { - if (key == "key50") { - hit++; - } - return true; - }); + store.createTransaction(Sink::Storage::ReadOnly) + .openDatabase() + .scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { + if (key == "key50") { + hit++; + } + return true; + }); QCOMPARE(hit, 1); } - //ensure we can read a single value + // ensure we can read a single value { int hit = 0; bool foundInvalidValue = false; Sink::Storage store(testDataPath, dbName); - store.createTransaction(Sink::Storage::ReadOnly).openDatabase().scan("key50", [&](const QByteArray &key, const QByteArray &value) -> bool { - if (key != "key50") { - foundInvalidValue = true; - } - hit++; - return true; - }); + store.createTransaction(Sink::Storage::ReadOnly) + .openDatabase() + .scan("key50", [&](const QByteArray &key, const QByteArray &value) -> bool { + if (key != "key50") { + foundInvalidValue = true; + } + hit++; + return true; + }); QVERIFY(!foundInvalidValue); QCOMPARE(hit, 1); } @@ -137,9 +142,7 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); transaction.openDatabase().scan("key1", [&](const QByteArray &key, const QByteArray &value) -> bool { - transaction.openDatabase().remove(key, [](const Sink::Storage::Error &) { - QVERIFY(false); - }); + transaction.openDatabase().remove(key, [](const Sink::Storage::Error &) { QVERIFY(false); }); return false; }); } @@ -148,12 +151,12 @@ private slots: { populate(3); Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); - store.createTransaction(Sink::Storage::ReadOnly).openDatabase().scan("key1", [&](const QByteArray &key, const QByteArray &value) -> bool { - store.createTransaction(Sink::Storage::ReadWrite).openDatabase().remove(key, [](const Sink::Storage::Error &) { - QVERIFY(false); + store.createTransaction(Sink::Storage::ReadOnly) + .openDatabase() + .scan("key1", [&](const QByteArray &key, const QByteArray &value) -> bool { + store.createTransaction(Sink::Storage::ReadWrite).openDatabase().remove(key, [](const Sink::Storage::Error &) { QVERIFY(false); }); + return false; }); - return false; - }); } void testReadEmptyDb() @@ -166,14 +169,15 @@ private slots: qDebug() << error.message; gotError = true; }); - int numValues = db.scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { - gotResult = true; - return false; - }, - [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + int numValues = db.scan("", + [&](const QByteArray &key, const QByteArray &value) -> bool { + gotResult = true; + return false; + }, + [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QCOMPARE(numValues, 0); QVERIFY(!gotResult); QVERIFY(!gotError); @@ -181,20 +185,20 @@ private slots: void testConcurrentRead() { - //With a count of 10000 this test is more likely to expose problems, but also takes some time to execute. + // With a count of 10000 this test is more likely to expose problems, but also takes some time to execute. const int count = 1000; populate(count); // QTest::qWait(500); - //We repeat the test a bunch of times since failing is relatively random + // We repeat the test a bunch of times since failing is relatively random for (int tries = 0; tries < 10; tries++) { bool error = false; - //Try to concurrently read - QList > futures; + // Try to concurrently read + QList> futures; const int concurrencyLevel = 20; for (int num = 0; num < concurrencyLevel; num++) { - futures << QtConcurrent::run([this, count, &error](){ + futures << QtConcurrent::run([this, count, &error]() { Sink::Storage storage(testDataPath, dbName, Sink::Storage::ReadOnly); Sink::Storage storage2(testDataPath, dbName + "2", Sink::Storage::ReadOnly); for (int i = 0; i < count; i++) { @@ -205,7 +209,7 @@ private slots: } }); } - for(auto future : futures) { + for (auto future : futures) { future.waitForFinished(); } QVERIFY(!error); @@ -226,17 +230,18 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("default", nullptr, false); - db.write("key","value"); - db.write("key","value"); + db.write("key", "value"); + db.write("key", "value"); - int numValues = db.scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { - gotResult = true; - return true; - }, - [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + int numValues = db.scan("", + [&](const QByteArray &key, const QByteArray &value) -> bool { + gotResult = true; + return true; + }, + [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QCOMPARE(numValues, 1); QVERIFY(!gotError); @@ -249,16 +254,17 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("default", nullptr, true); - db.write("key","value1"); - db.write("key","value2"); - int numValues = db.scan("key", [&](const QByteArray &key, const QByteArray &value) -> bool { - gotResult = true; - return true; - }, - [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + db.write("key", "value1"); + db.write("key", "value2"); + int numValues = db.scan("key", + [&](const QByteArray &key, const QByteArray &value) -> bool { + gotResult = true; + return true; + }, + [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QCOMPARE(numValues, 2); QVERIFY(!gotError); @@ -269,14 +275,17 @@ private slots: bool gotResult = false; bool gotError = false; Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadOnly); - int numValues = store.createTransaction(Sink::Storage::ReadOnly).openDatabase("test").scan("", [&](const QByteArray &key, const QByteArray &value) -> bool { - gotResult = true; - return false; - }, - [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + int numValues = store.createTransaction(Sink::Storage::ReadOnly) + .openDatabase("test") + .scan("", + [&](const QByteArray &key, const QByteArray &value) -> bool { + gotResult = true; + return false; + }, + [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QCOMPARE(numValues, 0); QVERIFY(!gotResult); QVERIFY(!gotError); @@ -286,10 +295,12 @@ private slots: { bool gotError = false; Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); - store.createTransaction(Sink::Storage::ReadWrite).openDatabase("test").write("key1", "value1", [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + store.createTransaction(Sink::Storage::ReadWrite) + .openDatabase("test") + .write("key1", "value1", [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QVERIFY(!gotError); } @@ -297,24 +308,24 @@ private slots: { bool gotError = false; Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); - store.createTransaction(Sink::Storage::ReadWrite).openDatabase("test", nullptr, true).write("key1", "value1", [&](const Sink::Storage::Error &error) { - qDebug() << error.message; - gotError = true; - }); + store.createTransaction(Sink::Storage::ReadWrite) + .openDatabase("test", nullptr, true) + .write("key1", "value1", [&](const Sink::Storage::Error &error) { + qDebug() << error.message; + gotError = true; + }); QVERIFY(!gotError); } - //By default we want only exact matches + // By default we want only exact matches void testSubstringKeys() { Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, true); - db.write("sub","value1"); - db.write("subsub","value2"); - int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { - return true; - }); + db.write("sub", "value1"); + db.write("subsub", "value2"); + int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { return true; }); QCOMPARE(numValues, 1); } @@ -324,12 +335,10 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, false); - db.write("sub","value1"); - db.write("subsub","value2"); - db.write("wubsub","value3"); - int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { - return true; - }, nullptr, true); + db.write("sub", "value1"); + db.write("subsub", "value2"); + db.write("wubsub", "value3"); + int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { return true; }, nullptr, true); QCOMPARE(numValues, 2); } @@ -339,12 +348,10 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, true); - db.write("sub","value1"); - db.write("subsub","value2"); - db.write("wubsub","value3"); - int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { - return true; - }, nullptr, true); + db.write("sub", "value1"); + db.write("subsub", "value2"); + db.write("wubsub", "value3"); + int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { return true; }, nullptr, true); QCOMPARE(numValues, 2); } @@ -354,9 +361,9 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, false); - db.write("sub_2","value2"); - db.write("sub_1","value1"); - db.write("sub_3","value3"); + db.write("sub_2", "value2"); + db.write("sub_1", "value1"); + db.write("sub_3", "value3"); QList results; int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { results << value; @@ -369,16 +376,14 @@ private slots: QCOMPARE(results.at(2), QByteArray("value3")); } - //Ensure we don't retrieve a key that is greater than the current key. We only want equal keys. + // Ensure we don't retrieve a key that is greater than the current key. We only want equal keys. void testKeyRange() { Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, true); - db.write("sub1","value1"); - int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { - return true; - }); + db.write("sub1", "value1"); + int numValues = db.scan("sub", [&](const QByteArray &key, const QByteArray &value) -> bool { return true; }); QCOMPARE(numValues, 0); } @@ -388,14 +393,12 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, false); - db.write("sub1","value1"); - db.write("sub2","value2"); - db.write("wub3","value3"); - db.write("wub4","value4"); + db.write("sub1", "value1"); + db.write("sub2", "value2"); + db.write("wub3", "value3"); + db.write("wub4", "value4"); QByteArray result; - db.findLatest("sub", [&](const QByteArray &key, const QByteArray &value) { - result = value; - }); + db.findLatest("sub", [&](const QByteArray &key, const QByteArray &value) { result = value; }); QCOMPARE(result, QByteArray("value2")); } @@ -405,11 +408,9 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, false); - db.write("sub2","value2"); + db.write("sub2", "value2"); QByteArray result; - db.findLatest("sub", [&](const QByteArray &key, const QByteArray &value) { - result = value; - }); + db.findLatest("sub", [&](const QByteArray &key, const QByteArray &value) { result = value; }); QCOMPARE(result, QByteArray("value2")); } @@ -419,12 +420,10 @@ private slots: Sink::Storage store(testDataPath, dbName, Sink::Storage::ReadWrite); auto transaction = store.createTransaction(Sink::Storage::ReadWrite); auto db = transaction.openDatabase("test", nullptr, false); - db.write("sub2","value2"); - db.write("wub3","value3"); + db.write("sub2", "value2"); + db.write("wub3", "value3"); QByteArray result; - db.findLatest("wub", [&](const QByteArray &key, const QByteArray &value) { - result = value; - }); + db.findLatest("wub", [&](const QByteArray &key, const QByteArray &value) { result = value; }); QCOMPARE(result, QByteArray("value3")); } diff --git a/tests/testimplementations.h b/tests/testimplementations.h index adfdab3..688875d 100644 --- a/tests/testimplementations.h +++ b/tests/testimplementations.h @@ -28,7 +28,7 @@ #include #include -//Replace with something different +// Replace with something different #include "event_generated.h" #include "mail_generated.h" #include "createentity_generated.h" @@ -36,37 +36,48 @@ class TestEventAdaptorFactory : public DomainTypeAdaptorFactory { public: - TestEventAdaptorFactory() - : DomainTypeAdaptorFactory() + TestEventAdaptorFactory() : DomainTypeAdaptorFactory() { } - virtual ~TestEventAdaptorFactory() {}; + virtual ~TestEventAdaptorFactory(){}; }; class TestMailAdaptorFactory : public DomainTypeAdaptorFactory { public: - TestMailAdaptorFactory() - : DomainTypeAdaptorFactory() + TestMailAdaptorFactory() : DomainTypeAdaptorFactory() { } - virtual ~TestMailAdaptorFactory() {}; + virtual ~TestMailAdaptorFactory(){}; }; class TestResourceAccess : public Sink::ResourceAccessInterface { Q_OBJECT public: - virtual ~TestResourceAccess() {}; - KAsync::Job sendCommand(int commandId) Q_DECL_OVERRIDE { return KAsync::null(); } - KAsync::Job sendCommand(int commandId, flatbuffers::FlatBufferBuilder &fbb) Q_DECL_OVERRIDE { return KAsync::null(); } - KAsync::Job synchronizeResource(bool remoteSync, bool localSync) Q_DECL_OVERRIDE { return KAsync::null(); } + virtual ~TestResourceAccess(){}; + KAsync::Job sendCommand(int commandId) Q_DECL_OVERRIDE + { + return KAsync::null(); + } + KAsync::Job sendCommand(int commandId, flatbuffers::FlatBufferBuilder &fbb) Q_DECL_OVERRIDE + { + return KAsync::null(); + } + KAsync::Job synchronizeResource(bool remoteSync, bool localSync) Q_DECL_OVERRIDE + { + return KAsync::null(); + } public slots: - void open() Q_DECL_OVERRIDE {} - void close() Q_DECL_OVERRIDE {} + void open() Q_DECL_OVERRIDE + { + } + void close() Q_DECL_OVERRIDE + { + } }; class TestResourceFacade : public Sink::GenericFacade @@ -75,11 +86,9 @@ public: TestResourceFacade(const QByteArray &instanceIdentifier, const QSharedPointer resourceAccess) : Sink::GenericFacade(instanceIdentifier, QSharedPointer::create(), resourceAccess) { - } virtual ~TestResourceFacade() { - } }; @@ -89,19 +98,16 @@ public: TestMailResourceFacade(const QByteArray &instanceIdentifier, const QSharedPointer resourceAccess) : Sink::GenericFacade(instanceIdentifier, QSharedPointer::create(), resourceAccess) { - } virtual ~TestMailResourceFacade() { - } }; class TestResource : public Sink::GenericResource { public: - TestResource(const QByteArray &instanceIdentifier, QSharedPointer pipeline) - : Sink::GenericResource(instanceIdentifier, pipeline) + TestResource(const QByteArray &instanceIdentifier, QSharedPointer pipeline) : Sink::GenericResource(instanceIdentifier, pipeline) { } @@ -126,4 +132,3 @@ QByteArray createCommand(const DomainType &domainObject, DomainTypeAdaptorFactor Sink::Commands::FinishCreateEntityBuffer(fbb, location); return QByteArray(reinterpret_cast(fbb.GetBufferPointer()), fbb.GetSize()); } - -- cgit v1.2.3