File indexing completed on 2024-03-24 03:57:47

0001 /*
0002     This file is part of the KDE project
0003     SPDX-FileCopyrightText: 2004-2014 David Faure <faure@kde.org>
0004 
0005     SPDX-License-Identifier: LGPL-2.0-or-later
0006 */
0007 
0008 #include <QTest>
0009 
0010 #include <QThreadPool>
0011 #include <QtConcurrentRun>
0012 
0013 #include "kio/filecopyjob.h"
0014 #include "kiotesthelper.h" // homeTmpDir, createTestFile etc.
0015 
0016 class KIOThreadTest : public QObject
0017 {
0018     Q_OBJECT
0019 private Q_SLOTS:
0020     void initTestCase();
0021     void concurrentCopying();
0022     void cleanupTestCase();
0023 
0024 private:
0025     struct FileData;
0026     bool copyLocalFile(FileData *fileData);
0027 };
0028 
0029 void KIOThreadTest::initTestCase()
0030 {
0031     QStandardPaths::setTestModeEnabled(true);
0032 
0033     // Start with a clean base dir
0034     cleanupTestCase();
0035     homeTmpDir(); // create it
0036 
0037     QCOMPARE(sizeof(int), sizeof(QAtomicInt));
0038 
0039     Q_UNUSED(createTestDirectory);
0040 }
0041 
0042 void KIOThreadTest::cleanupTestCase()
0043 {
0044     QDir(homeTmpDir()).removeRecursively();
0045 }
0046 
0047 struct KIOThreadTest::FileData {
0048     QString src;
0049     QString dest;
0050 };
0051 
0052 bool KIOThreadTest::copyLocalFile(FileData *fileData)
0053 {
0054     // to verify the test harness: return QFile::copy(fileData->src, fileData->dest);
0055 
0056     const QUrl u = QUrl::fromLocalFile(fileData->src);
0057     const QUrl d = QUrl::fromLocalFile(fileData->dest);
0058 
0059     // copy the file with file_copy
0060     KIO::Job *job = KIO::file_copy(u, d, -1, KIO::HideProgressInfo);
0061     // qDebug() << job << u << d;
0062     job->setUiDelegate(nullptr);
0063     bool ret = job->exec();
0064     // qDebug() << job << "done";
0065     return ret;
0066 }
0067 
0068 void KIOThreadTest::concurrentCopying()
0069 {
0070     const int numThreads = 20;
0071     QList<FileData> data(numThreads);
0072     for (int i = 0; i < numThreads; ++i) {
0073         data[i].src = homeTmpDir() + "file" + QString::number(i);
0074         data[i].dest = homeTmpDir() + "file" + QString::number(i) + "_copied";
0075         createTestFile(data[i].src);
0076     }
0077     QThreadPool tp;
0078     tp.setMaxThreadCount(numThreads);
0079     QList<QFuture<bool>> futures(numThreads);
0080     for (int i = 0; i < numThreads; ++i) {
0081         futures[i] = QtConcurrent::run(&tp, &KIOThreadTest::copyLocalFile, this, &data[i]);
0082     }
0083     QVERIFY(tp.waitForDone(60000));
0084 
0085     for (int i = 0; i < numThreads; ++i) {
0086         QVERIFY(QFile::exists(data[i].dest));
0087         QVERIFY(futures.at(i).result());
0088     }
0089 }
0090 
0091 QTEST_MAIN(KIOThreadTest)
0092 #include "threadtest.moc"