void KInotifyTest::testMoveRootFolder() { // create some test folders QTemporaryDir dir; const QString src(QStringLiteral("%1/randomJunk1").arg(dir.path())); const QString dest(QStringLiteral("%1/randomJunk2").arg(dir.path())); mkdir(src); // start watching the new subfolder only KInotify kn(nullptr /*no config*/); kn.addWatch(src, KInotify::EventAll); // listen for the moved signal QSignalSpy spy(&kn, SIGNAL(moved(QString,QString))); // actually move the file QFile::rename(src, dest); // check the desired signal QEXPECT_FAIL("", "KInotify cannot handle moving of top-level folders.", Abort); QVERIFY(spy.wait(500)); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), src); QCOMPARE(args.at(1).toString(), dest); // check the path cache QVERIFY(!kn.watchingPath(src)); QVERIFY(kn.watchingPath(dest)); }
void KInotifyTest::testRenameFolder() { // create some test files QTemporaryDir dir; const QString f1(QStringLiteral("%1/randomJunk1").arg(dir.path())); mkdir(f1); // start the inotify watcher KInotify kn(nullptr /*no config*/); kn.addWatch(dir.path(), KInotify::EventAll); // listen to the desired signal QSignalSpy spy(&kn, SIGNAL(moved(QString,QString))); // actually move the file const QString f2(QStringLiteral("%1/randomJunk2").arg(dir.path())); QFile::rename(f1, f2); // check the desired signal QVERIFY(spy.wait()); QCOMPARE(spy.count(), 1); QList<QVariant> args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), f1); QCOMPARE(args.at(1).toString(), f2); // check the path cache QVERIFY(!kn.watchingPath(f1)); QVERIFY(kn.watchingPath(f2)); // test a subsequent rename const QString f3(QStringLiteral("%1/randomJunk3").arg(dir.path())); QFile::rename(f2, f3); // check the desired signal QVERIFY(spy.wait()); QCOMPARE(spy.count(), 1); args = spy.takeFirst(); QCOMPARE(args.at(0).toString(), f2); QCOMPARE(args.at(1).toString(), f3); // check the path cache QVERIFY(!kn.watchingPath(f1)); QVERIFY(!kn.watchingPath(f2)); QVERIFY(kn.watchingPath(f3)); // KInotify claims it has updated its data structures, lets see if that is true // by creating a file in the new folder // listen to the desired signal const QString f4(QStringLiteral("%1/somefile").arg(f3)); QSignalSpy createdSpy(&kn, SIGNAL(created(QString,bool))); // test creating a file touchFile(f4); QVERIFY(createdSpy.wait()); QCOMPARE(createdSpy.count(), 1); QCOMPARE(createdSpy.takeFirst().at(0).toString(), f4); }
bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const { PuppetBuildProgressDialog progressDialog; m_compileLog.clear(); QTemporaryDir buildDirectory; bool buildSucceeded = false; if (qtIsSupported()) { if (buildDirectory.isValid()) { QStringList qmakeArguments; qmakeArguments.append(QStringLiteral("-r")); qmakeArguments.append(QStringLiteral("-after")); qmakeArguments.append(QStringLiteral("DESTDIR=") + qmlpuppetDirectory(UserSpacePuppet)); #ifndef QT_DEBUG qmakeArguments.append(QStringLiteral("CONFIG+=release")); #endif qmakeArguments.append(qmlPuppetProjectFilePath); buildSucceeded = startBuildProcess(buildDirectory.path(), qmakeCommand(), qmakeArguments); if (buildSucceeded) { progressDialog.show(); buildSucceeded = startBuildProcess(buildDirectory.path(), buildCommand(), QStringList(), &progressDialog); progressDialog.hide(); } } else { buildSucceeded = true; } } m_useOnlyFallbackPuppet = !buildSucceeded; // fall back to creator puppet and don't compile again return buildSucceeded; }
FstabEntryList lookForFstabEntries( const QString& partitionPath ) { FstabEntryList fstabEntries; QTemporaryDir mountsDir; int exit = QProcess::execute( "mount", { partitionPath, mountsDir.path() } ); if ( !exit ) // if all is well { QFile fstabFile( mountsDir.path() + "/etc/fstab" ); if ( fstabFile.open( QIODevice::ReadOnly | QIODevice::Text ) ) { QStringList fstabLines = QString::fromLocal8Bit( fstabFile.readAll() ) .split( '\n' ); foreach ( const QString& rawLine, fstabLines ) { QString line = rawLine.simplified(); if ( line.startsWith( '#' ) ) continue; QStringList splitLine = line.split( ' ' ); if ( splitLine.length() != 6 ) continue; fstabEntries.append( { splitLine.at( 0 ), // path, or UUID, or LABEL, etc. splitLine.at( 1 ), // mount point splitLine.at( 2 ), // fs type splitLine.at( 3 ), // options splitLine.at( 4 ).toInt(), //dump splitLine.at( 5 ).toInt() //pass } ); }
void TestBuddies::testDisableAll() { /* 6. Disable buddy option, Disable open next to active tab Open foo.cpp bar.h foo.h Activate bar.h Open bar.cpp Verify order (foo.cpp bar.h foo.h bar.cpp) Verify that bar.cpp is activated*/ enableBuddies(false); enableOpenAfterCurrent(false); QTemporaryDir tempDirA; QDir dirA(tempDirA.path()); createFile(dirA, "foo.h"); createFile(dirA, "foo.cpp"); createFile(dirA, "bar.h"); createFile(dirA, "bar.cpp"); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("foo.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("bar.h"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("foo.h"))); Sublime::Area *area = m_uiController->activeArea(); Sublime::AreaIndex* areaIndex = area->indexOf(toSublimeWindow(m_uiController->activeMainWindow())->activeView()); //activate bar.h toSublimeWindow(m_uiController->activeMainWindow())->activateView(areaIndex->views().value(1)); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("bar.cpp"))); verifyFilename(areaIndex->views().value(0), "foo.cpp"); verifyFilename(areaIndex->views().value(1), "bar.h"); verifyFilename(areaIndex->views().value(2), "foo.h"); verifyFilename(areaIndex->views().value(3), "bar.cpp"); verifyFilename(toSublimeWindow(m_uiController->activeMainWindow())->activeView(), "bar.cpp"); }
void TestBuddies::testMultipleFolders() { /* 4. Multiple folders: Activate buddy option Open f/a.cpp f/xyz.cpp g/a.h Verify g/a.h is activated Verify order (f/a.cpp f/xyz.cpp g/a.h)*/ enableBuddies(); enableOpenAfterCurrent(); QTemporaryDir tempDirA; QDir dirA(tempDirA.path()); createFile(dirA, "a.cpp"); createFile(dirA, "x.cpp"); QTemporaryDir tempDirB; QDir dirB(tempDirB.path()); createFile(dirB, "a.h"); // different folder => not dirA/a.cpp's buddy! m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("a.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("x.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirB.filePath("a.h"))); Sublime::Area *area = m_uiController->activeArea(); Sublime::AreaIndex* areaIndex = area->indexOf(toSublimeWindow(m_uiController->activeMainWindow())->activeView()); verifyFilename(areaIndex->views().value(0), "a.cpp"); verifyFilename(areaIndex->views().value(1), "x.cpp"); verifyFilename(areaIndex->views().value(2), "a.h"); verifyFilename(toSublimeWindow(m_uiController->activeMainWindow())->activeView(), "a.h"); }
void TestBuddies::testMultiDotFilenames() { enableBuddies(); enableOpenAfterCurrent(); QTemporaryDir tempDirA; QDir dirA(tempDirA.path()); createFile(dirA, "a.cpp"); createFile(dirA, "lots.of.dots.cpp"); createFile(dirA, "b.cpp"); createFile(dirA, "lots.of.dots.h"); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("a.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("lots.of.dots.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("b.cpp"))); m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("lots.of.dots.h"))); Sublime::Area *area = m_uiController->activeArea(); Sublime::AreaIndex* areaIndex = area->indexOf(toSublimeWindow(m_uiController->activeMainWindow())->activeView()); QCOMPARE(m_documentController->openDocuments().count(), 4); //QCOMPARE(m_sublimeController->documents().count(), 4); QCOMPARE(areaIndex->viewCount(), 4); verifyFilename(areaIndex->views().value(0), "a.cpp"); verifyFilename(areaIndex->views().value(1), "lots.of.dots.h"); verifyFilename(areaIndex->views().value(2), "lots.of.dots.cpp"); verifyFilename(areaIndex->views().value(3), "b.cpp"); }
void KInotifyTest::testCreateFolder() { QTemporaryDir dir; // start the inotify watcher KInotify kn(nullptr /*no config*/); kn.addWatch(dir.path(), KInotify::EventAll); // listen to the desired signal QSignalSpy createdSpy(&kn, SIGNAL(created(QString,bool))); // create the subdir const QString d1(QStringLiteral("%1/randomJunk1").arg(dir.path())); mkdir(d1); QVERIFY(createdSpy.wait()); QCOMPARE(createdSpy.count(), 1); QCOMPARE(createdSpy.takeFirst().at(0).toString(), d1); QVERIFY(kn.watchingPath(d1)); // lets go one level deeper const QString d2 = QStringLiteral("%1/subdir1").arg(d1); mkdir(d2); QVERIFY(createdSpy.wait()); QCOMPARE(createdSpy.count(), 1); QCOMPARE(createdSpy.takeFirst().at(0).toString(), d2); QVERIFY(kn.watchingPath(d2)); // although we are in the folder test lets try creating a file const QString f1 = QStringLiteral("%1/somefile1").arg(d2); touchFile(f1); QVERIFY(createdSpy.wait()); QCOMPARE(createdSpy.count(), 1); QCOMPARE(createdSpy.takeFirst().at(0).toString(), f1); }
void Tests::doBasicTests(const QString &pFileName) { // Save the given COMBINE archive to the given file QString fileName = pFileName.isEmpty()?mCombineArchive->fileName():pFileName; mCombineArchive->save(fileName); QVERIFY(QFile::exists(fileName)); // Unzip our COMBINE archive and make sure that its manifest is correct and // that the various files are present OpenCOR::ZIPSupport::QZipReader zipReader(fileName); QTemporaryDir temporaryDir; QVERIFY(zipReader.extractAll(temporaryDir.path())); QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+"manifest.xml"), OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/manifest.xml"))); for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j) QVERIFY(QFile::exists(temporaryDir.path()+QDir::separator()+QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)))); } }
void Tests::basicTests() { // Create a simple COMBINE archive that contains various files QString fileName = OpenCOR::Core::temporaryFileName(); OpenCOR::COMBINESupport::CombineArchive combineArchive(fileName); int counter = 0; for (int i = 1; i <= 3; ++i) { for (int j = 1; j <= 3; ++j, ++counter) { combineArchive.addFile(QDir::currentPath()+QDir::separator()+OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)), QString("dir0%1/file0%2.txt").arg(QString::number(i), QString::number(j)), OpenCOR::COMBINESupport::CombineArchiveFile::Format(1+counter%4), !(counter%2)); } } combineArchive.save(); QVERIFY(QFile::exists(fileName)); // Unzip our COMBINE archive OpenCOR::ZIPSupport::QZipReader zipReader(fileName); QTemporaryDir temporaryDir; QVERIFY(zipReader.extractAll(temporaryDir.path())); zipReader.close(); // Make sure that our COMBINE archive's manifest is correct QCOMPARE(OpenCOR::fileContents(temporaryDir.path()+QDir::separator()+"manifest.xml"), OpenCOR::fileContents(OpenCOR::fileName("src/plugins/support/COMBINESupport/tests/data/manifest.xml"))); }
void KArchiveTest::testZipAddLocalDirectory() { // Prepare local dir QTemporaryDir tmpDir; const QString dirName = tmpDir.path() + '/'; const QByteArray file1Data = "Hello Shantanu"; const QString file1 = QStringLiteral("file1"); QVERIFY(writeFile(dirName, file1, file1Data)); { KZip zip(s_zipFileName); QVERIFY(zip.open(QIODevice::WriteOnly)); QVERIFY(zip.addLocalDirectory(dirName, ".")); QVERIFY(zip.close()); } { KZip zip(s_zipFileName); QVERIFY(zip.open(QIODevice::ReadOnly)); const KArchiveDirectory *dir = zip.directory(); QVERIFY(dir != nullptr); const KArchiveEntry *e = dir->entry(file1); QVERIFY(e && e->isFile()); const KArchiveFile *f = (KArchiveFile *)e; QCOMPARE(f->data(), file1Data); } }
void MoveTest::testMoving() { QTemporaryDir temporaryDir; QFETCH(QString, archiveName); const QString archivePath = temporaryDir.path() + QLatin1Char('/') + archiveName; QVERIFY(QFile::copy(QFINDTESTDATA(QStringLiteral("data/") + archiveName), archivePath)); QFETCH(Plugin*, plugin); QVERIFY(plugin); auto loadJob = Archive::load(archivePath, plugin); QVERIFY(loadJob); loadJob->setAutoDelete(false); TestHelper::startAndWaitForResult(loadJob); auto archive = loadJob->archive(); QVERIFY(archive); if (!archive->isValid()) { QSKIP("Could not find a plugin to handle the archive. Skipping test.", SkipSingle); } QFETCH(QVector<Archive::Entry*>, targetEntries); QFETCH(Archive::Entry*, destination); QFETCH(QStringList, expectedNewPaths); // Retrieve current paths in the archive. QStringList oldPaths = getEntryPaths(archive); // Check that the entries to be moved are in the archive. foreach (const auto entry, targetEntries) { QVERIFY(oldPaths.contains(entry->fullPath())); }
void TestShpFilter::testWritePolygonZFile() const { CCVector3d bbMin(1422671.7232666016, 4188903.4295959473, 71.99445343017578); CCVector3d shift = ccGlobalShiftManager::BestShift(bbMin); bool shiftEnabled = true; ccHObject container; FileIOFilter::LoadParameters params; params.alwaysDisplayLoadDialog = false; params.shiftHandlingMode = ccGlobalShiftManager::Mode::NO_DIALOG; params.coordinatesShiftEnabled = &shiftEnabled; params.coordinatesShift = &shift; params.preserveShiftOnSave = true; ShpFilter filter; CC_FILE_ERROR error = filter.loadFile(POLYGONZ_FILE, container, params); QVERIFY(error == CC_FERR_NO_ERROR); QTemporaryDir tmpDir; QString tmpMultipatch = tmpDir.path() + "polygon_z.shp"; FileIOFilter::SaveParameters saveParams; saveParams.alwaysDisplaySaveDialog = false; filter.save3DPolyAs2D(false); filter.treatClosedPolylinesAsPolygons(true); error = filter.saveToFile(&container, tmpMultipatch, saveParams); QVERIFY(error == CC_FERR_NO_ERROR); readPolygonZFile(tmpMultipatch); }
bool GeneratePage::unpackArchive(const KArchiveDirectory *dir, const QString &dest) { qCDebug(KAPPTEMPLATE) << "unpacking dir:" << dir->name() << "to" << dest; QStringList entries = dir->entries(); qCDebug(KAPPTEMPLATE) << "entries:" << entries.join(","); QTemporaryDir tdir; bool ret = true; //create path were we want copy files to if (!QDir::root().mkpath(dest)) { displayError(i18n("%1 cannot be created.", dest)); return false; } int progress = 0; bool failed = false; foreach (const QString &entry, entries) { progress++; ui_generate.progressBar->setValue((progress / entries.size()) * 100); if (entry.endsWith(".kdevtemplate")) continue; if (entry == templateName + ".png") continue; if (dir->entry(entry)->isDirectory()) { const KArchiveDirectory *file = dynamic_cast<const KArchiveDirectory *>(dir->entry(entry)); QString newdest = dest + "/" + file->name(); if (!QFileInfo(newdest).exists()) { if (!QDir::root().mkdir(newdest)) { displayError(i18n("Path %1 could not be created.", newdest)); return false; } } ret |= unpackArchive(file, newdest); } else if (dir->entry(entry)->isFile()) { const KArchiveFile *file = dynamic_cast<const KArchiveFile *>(dir->entry(entry)); file->copyTo(tdir.path()); QString destName = KMacroExpander::expandMacros(dest + '/' + file->name(), m_variables); if (QFile(QDir::cleanPath(tdir.path() + '/' + file->name())).copy(destName)) { if (!extractFileMacros(destName)) { displayError(i18n("Failed to integrate your project information into " "the file %1. The project has not been generated and " "all temporary files will be removed.", destName)); failed = true; break; } } else { displayError(i18n("Could not copy template file to %1.", destName)); failed = true; break; } } }
terrama2::core::DataSetSeries terrama2::core::DataAccessorDcpToa5::getSeries(const std::string& uri, const terrama2::core::Filter& filter, terrama2::core::DataSetPtr dataSet) const { std::string mask = getMask(dataSet); std::string folder = getFolder(dataSet); QTemporaryDir tempBaseDir; if(!tempBaseDir.isValid()) { QString errMsg = QObject::tr("Can't create temporary folder."); TERRAMA2_LOG_ERROR() << errMsg; throw DataAccessException() << ErrorDescription(errMsg); } QDir tempDir(tempBaseDir.path()); tempDir.mkdir(QString::fromStdString(folder)); tempDir.cd(QString::fromStdString(folder)); QUrl url((uri+"/"+folder+"/"+mask).c_str()); QFileInfo originalInfo(url.path()); QFile file(url.path()); QFile tempFile(tempDir.path()+"/"+originalInfo.fileName()); if(!file.open(QIODevice::ReadOnly)) { QString errMsg = QObject::tr("Can't open file: dataset %1.").arg(dataSet->id); TERRAMA2_LOG_ERROR() << errMsg; throw DataAccessException() << ErrorDescription(errMsg); } if(!tempFile.open(QIODevice::ReadWrite)) { QString errMsg = QObject::tr("Can't open temporary file: dataset %1.").arg(dataSet->id); TERRAMA2_LOG_ERROR() << errMsg; throw DataAccessException() << ErrorDescription(errMsg); } file.readLine();//ignore first line tempFile.write(file.readLine()); //headers line //ignore third and fourth lines file.readLine(); file.readLine(); //read all file tempFile.write(file.readAll()); //headers line //update file path std::string tempUri = "file://"+tempBaseDir.path().toStdString(); file.close(); tempFile.close(); auto dataSeries = terrama2::core::DataAccessorFile::getSeries(tempUri, filter, dataSet); return dataSeries; }
void tst_qmldiskcache::cppRegisteredSingletonDependency() { qmlClearTypeRegistrations(); QScopedPointer<QQmlEngine> engine(new QQmlEngine); QTemporaryDir tempDir; QVERIFY(tempDir.isValid()); const auto writeTempFile = [&tempDir](const QString &fileName, const char *contents) { QFile f(tempDir.path() + '/' + fileName); const bool ok = f.open(QIODevice::WriteOnly | QIODevice::Truncate); Q_ASSERT(ok); f.write(contents); return f.fileName(); }; writeTempFile("MySingleton.qml", "import QtQml 2.0\npragma Singleton\nQtObject { property int value: 42 }"); qmlRegisterSingletonType(QUrl::fromLocalFile(tempDir.path() + QLatin1String("/MySingleton.qml")), "CppRegisteredSingletonDependency", 1, 0, "Singly"); const QString testFilePath = writeTempFile("main.qml", "import QtQml 2.0\nimport CppRegisteredSingletonDependency 1.0\nQtObject {\n" " function getValue() { return Singly.value; }\n" "}"); { CleanlyLoadingComponent component(engine.data(), QUrl::fromLocalFile(testFilePath)); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); QVariant value; QVERIFY(QMetaObject::invokeMethod(obj.data(), "getValue", Q_RETURN_ARG(QVariant, value))); QCOMPARE(value.toInt(), 42); } const QString testFileCachePath = testFilePath + QLatin1Char('c'); QVERIFY(QFile::exists(testFileCachePath)); QDateTime initialCacheTimeStamp = QFileInfo(testFileCachePath).lastModified(); engine.reset(new QQmlEngine); waitForFileSystem(); writeTempFile("MySingleton.qml", "import QtQml 2.0\npragma Singleton\nQtObject { property int value: 100 }"); waitForFileSystem(); { CleanlyLoadingComponent component(engine.data(), QUrl::fromLocalFile(testFilePath)); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); { QVERIFY(QFile::exists(testFileCachePath)); QDateTime newCacheTimeStamp = QFileInfo(testFileCachePath).lastModified(); QVERIFY2(newCacheTimeStamp > initialCacheTimeStamp, qPrintable(newCacheTimeStamp.toString())); } QVariant value; QVERIFY(QMetaObject::invokeMethod(obj.data(), "getValue", Q_RETURN_ARG(QVariant, value))); QCOMPARE(value.toInt(), 100); } }
void tst_QTemporaryDir::construction() { QTemporaryDir dir; QString tmp = QDir::tempPath(); QCOMPARE(dir.path().left(tmp.size()), tmp); QVERIFY(dir.path().contains("tst_qtemporarydir")); QVERIFY(QFileInfo(dir.path()).isDir()); }
void Tests::basicTests() { // Some basic tests to save our COMBINE archive either directly or to a // different file and checking that its contents is sound QString otherFileName = OpenCOR::Core::temporaryFileName(); doBasicTests(); doBasicTests(otherFileName); // Check that we can load our other COMBINE archive and save it in yet // another file OpenCOR::COMBINESupport::CombineArchive otherCombineArchive(otherFileName); QString yetAnotherFileName = OpenCOR::Core::temporaryFileName(); QVERIFY(otherCombineArchive.load()); QVERIFY(otherCombineArchive.isValid()); QVERIFY(otherCombineArchive.save(yetAnotherFileName)); // Unzip our two COMBINE archives and make sure that their contents is the // same // Note: the original plan was to check that the SHA-1 value of the two // files was the same, but the fact is that the ZIP file format // contains various date and time information, so the SHA-1 value of // two files may be different... QTemporaryDir temporaryDir; QString otherDir = temporaryDir.path()+"/otherDir"; QString yetAnotherDir = temporaryDir.path()+"/yetAnotherDir"; OpenCOR::ZIPSupport::QZipReader otherZipReader(otherFileName); OpenCOR::ZIPSupport::QZipReader yetAnotherZipReader(yetAnotherFileName); QVERIFY(otherZipReader.extractAll(otherDir)); QVERIFY(yetAnotherZipReader.extractAll(yetAnotherDir)); QDirIterator dirIterator(otherDir, QStringList() << "*", QDir::Files, QDirIterator::Subdirectories); while (dirIterator.hasNext()) { QString otherFileName = dirIterator.next(); QString yetAnotherFileName = otherFileName.replace(otherDir, yetAnotherDir); QByteArray otherFileContents; QByteArray yetAnotherFileContents; QVERIFY(OpenCOR::Core::readFileContentsFromFile(otherFileName, otherFileContents)); QVERIFY(OpenCOR::Core::readFileContentsFromFile(yetAnotherFileName, yetAnotherFileContents)); QCOMPARE(OpenCOR::Core::sha1(otherFileContents), OpenCOR::Core::sha1(yetAnotherFileContents)); } // Clean up after ourselves QFile::remove(otherFileName); QFile::remove(yetAnotherFileName); }
void CreateFileTest::createFileTest() { QTemporaryDir dir; QVERIFY(dir.isValid()); const auto filePath = QDir::cleanPath(dir.path() + "/subA/subB/file.txt"); QVERIFY(!QFile::exists(filePath)); QVERIFY(createFile(filePath)); QVERIFY(QFile::exists(filePath)); }
void TestBuddies::testDUChainBuddyVote() { /* * Test that the DUChain buddy system finds the buddy file with the most * common declarations/definitions */ enableBuddies(); enableOpenAfterCurrent(); QTemporaryDir dirA; TestFile header("void func1();\nvoid func2();\nvoid func3();\n", "h", nullptr, dirA.path()); TestFile source1( QString("#include \"%1\"\nvoid func1() {}\n").arg(header.url().toUrl().fileName()), "cpp", nullptr, dirA.path() ); TestFile source2( QString("#include \"%1\"\nvoid func2() {}\nvoid func3() {}\n").arg(header.url().toUrl().fileName()), "cpp", nullptr, dirA.path() ); // -> buddy(header) should resolve to source2 header.parseAndWait(); source1.parseAndWait(); source2.parseAndWait(); // Test IBuddyDocumentFinder::getPotentialBuddies() QMimeDatabase db; IBuddyDocumentFinder* sourceBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(source1.url().toUrl()).name()); QVector< QUrl > sourceBuddies = sourceBuddyFinder->getPotentialBuddies(source1.url().toUrl()); if (!sourceBuddies.contains(header.url().toUrl())) { qDebug() << "got source buddies: " << sourceBuddies; qDebug() << "expected: " << header.url().toUrl(); QFAIL("Failed to find buddy for source file"); } IBuddyDocumentFinder* source2BuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(source2.url().toUrl()).name()); QVector< QUrl > source2Buddies = source2BuddyFinder->getPotentialBuddies(source2.url().toUrl()); if (!source2Buddies.contains(header.url().toUrl())) { qDebug() << "got source2 buddies: " << source2Buddies; qDebug() << "expected: " << header.url().toUrl(); QFAIL("Failed to find buddy for source2 file"); } IBuddyDocumentFinder* headerBuddyFinder = IBuddyDocumentFinder::finderForMimeType(db.mimeTypeForUrl(header.url().toUrl()).name()); QVector< QUrl > headerBuddies = headerBuddyFinder->getPotentialBuddies(header.url().toUrl()); if (!headerBuddies.contains(source2.url().toUrl())) { qDebug() << "got header buddies: " << headerBuddies; qDebug() << "expected: " << source2.url().toUrl(); QFAIL("Failed to find buddy for header file"); } QVERIFY2(!headerBuddies.contains(source1.url().toUrl()), "header buddy list contains weaker file"); }
static QUrl createFile(const QString& fileContents) { static QTemporaryDir dirA; static int i = 0; ++i; QFile file(dirA.path() + '/' + QString::number(i) + ".cpp"); file.open(QIODevice::WriteOnly | QIODevice::Text); file.write(fileContents.toUtf8()); file.close(); return QUrl::fromLocalFile(file.fileName()); }
void CreateFileTest::createFileInDirectoryTest() { QTemporaryDir dir; QVERIFY(dir.isValid()); QString fileName = "file.txt"; const auto dirPath = QDir::cleanPath( dir.path() + "/subC" ); const auto filePath = QDir::cleanPath( dirPath + "/" + fileName ); QVERIFY(!QFile::exists(filePath)); QVERIFY(createFileInDirectory(dirPath, fileName)); QVERIFY(QFile::exists(filePath)); }
void TestQgsProject::testPathResolver() { // Test resolver with a non existing file path QgsPathResolver resolverLegacy( QStringLiteral( "/home/qgis/test.qgs" ) ); QCOMPARE( resolverLegacy.readPath( QString() ), QString() ); QCOMPARE( resolverLegacy.writePath( QString() ), QString() ); QCOMPARE( resolverLegacy.writePath( "/home/qgis/file1.txt" ), QString( "./file1.txt" ) ); QCOMPARE( resolverLegacy.writePath( "/home/qgis/subdir/file1.txt" ), QString( "./subdir/file1.txt" ) ); QCOMPARE( resolverLegacy.writePath( "/home/file1.txt" ), QString( "../file1.txt" ) ); QCOMPARE( resolverLegacy.readPath( "./file1.txt" ), QString( "/home/qgis/file1.txt" ) ); QCOMPARE( resolverLegacy.readPath( "./subdir/file1.txt" ), QString( "/home/qgis/subdir/file1.txt" ) ); QCOMPARE( resolverLegacy.readPath( "../file1.txt" ), QString( "/home/file1.txt" ) ); QCOMPARE( resolverLegacy.readPath( "/home/qgis/file1.txt" ), QString( "/home/qgis/file1.txt" ) ); // Test resolver with existing file path QTemporaryDir tmpDir; QString tmpDirName = tmpDir.path(); QDir dir( tmpDirName ); dir.mkpath( tmpDirName + "/home/qgis/" ); QgsPathResolver resolverRel( QString( tmpDirName + "/home/qgis/test.qgs" ) ); QCOMPARE( resolverRel.readPath( QString() ), QString() ); QCOMPARE( resolverRel.writePath( QString() ), QString() ); QCOMPARE( resolverRel.writePath( tmpDirName + "/home/qgis/file1.txt" ), QString( "./file1.txt" ) ); QCOMPARE( resolverRel.writePath( tmpDirName + "/home/qgis/subdir/file1.txt" ), QString( "./subdir/file1.txt" ) ); QCOMPARE( resolverRel.writePath( tmpDirName + "/home/file1.txt" ), QString( "../file1.txt" ) ); QCOMPARE( resolverRel.readPath( "./file1.txt" ), QString( tmpDirName + "/home/qgis/file1.txt" ) ); QCOMPARE( resolverRel.readPath( "./subdir/file1.txt" ), QString( tmpDirName + "/home/qgis/subdir/file1.txt" ) ); QCOMPARE( resolverRel.readPath( "../file1.txt" ), QString( tmpDirName + "/home/file1.txt" ) ); QCOMPARE( resolverRel.readPath( tmpDirName + "/home/qgis/file1.txt" ), QString( tmpDirName + "/home/qgis/file1.txt" ) ); // test older style relative path - file must exist for this to work QTemporaryFile tmpFile; tmpFile.open(); // fileName is not available until we open the file QString tmpName = tmpFile.fileName(); tmpFile.close(); QgsPathResolver tempRel( tmpName ); QFileInfo fi( tmpName ); QFile testFile( fi.path() + QStringLiteral( "/file1.txt" ) ); QVERIFY( testFile.open( QIODevice::WriteOnly | QIODevice::Text ) ); testFile.close(); QVERIFY( QFile::exists( fi.path() + QStringLiteral( "/file1.txt" ) ) ); QCOMPARE( tempRel.readPath( "file1.txt" ), fi.path() + QStringLiteral( "/file1.txt" ) ); QgsPathResolver resolverAbs; QCOMPARE( resolverAbs.writePath( "/home/qgis/file1.txt" ), QString( "/home/qgis/file1.txt" ) ); QCOMPARE( resolverAbs.readPath( "/home/qgis/file1.txt" ), QString( "/home/qgis/file1.txt" ) ); QCOMPARE( resolverAbs.readPath( "./file1.txt" ), QString( "./file1.txt" ) ); // TODO: test non-canonical paths - there are inconsistencies in the implementation // e.g. base filename "/home/qgis/../test.qgs" resolving "/home/qgis/../file1.txt" back and forth }
void tst_qmldiskcache::singletonDependency() { QScopedPointer<QQmlEngine> engine(new QQmlEngine); QTemporaryDir tempDir; QVERIFY(tempDir.isValid()); const auto writeTempFile = [&tempDir](const QString &fileName, const char *contents) { QFile f(tempDir.path() + '/' + fileName); const bool ok = f.open(QIODevice::WriteOnly | QIODevice::Truncate); Q_ASSERT(ok); f.write(contents); return f.fileName(); }; writeTempFile("MySingleton.qml", "import QtQml 2.0\npragma Singleton\nQtObject { property int value: 42 }"); writeTempFile("qmldir", "singleton MySingleton 1.0 MySingleton.qml"); const QString testFilePath = writeTempFile("main.qml", "import QtQml 2.0\nimport \".\"\nQtObject {\n" " property int value: MySingleton.value\n" "}"); { CleanlyLoadingComponent component(engine.data(), QUrl::fromLocalFile(testFilePath)); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); QCOMPARE(obj->property("value").toInt(), 42); } const QString testFileCachePath = testFilePath + QLatin1Char('c'); QVERIFY(QFile::exists(testFileCachePath)); QDateTime initialCacheTimeStamp = QFileInfo(testFileCachePath).lastModified(); engine.reset(new QQmlEngine); waitForFileSystem(); writeTempFile("MySingleton.qml", "import QtQml 2.0\npragma Singleton\nQtObject { property int value: 100 }"); waitForFileSystem(); { CleanlyLoadingComponent component(engine.data(), QUrl::fromLocalFile(testFilePath)); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); QCOMPARE(obj->property("value").toInt(), 100); } { QVERIFY(QFile::exists(testFileCachePath)); QDateTime newCacheTimeStamp = QFileInfo(testFileCachePath).lastModified(); QVERIFY2(newCacheTimeStamp > initialCacheTimeStamp, qPrintable(newCacheTimeStamp.toString())); } }
void KIOPasteTest::testPasteJob() { QFETCH(QList<QUrl>, urls); QFETCH(bool, data); QFETCH(bool, cut); QFETCH(QString, expectedFileName); QMimeData mimeData; bool isDir = false; bool isFile = false; if (!urls.isEmpty()) { mimeData.setUrls(urls); QFileInfo fileInfo(urls.first().toLocalFile()); isDir = fileInfo.isDir(); isFile = fileInfo.isFile(); } if (data) { mimeData.setText(QStringLiteral("Hello world")); } KIO::setClipboardDataCut(&mimeData, cut); QTemporaryDir destTempDir; QVERIFY(destTempDir.isValid()); const QString destDir = destTempDir.path(); KIO::Job *job = KIO::paste(&mimeData, QUrl::fromLocalFile(destDir), KIO::HideProgressInfo); QSignalSpy spy(job, SIGNAL(itemCreated(QUrl))); QVERIFY(spy.isValid()); job->setUiDelegate(0); const bool expectedSuccess = !expectedFileName.isEmpty(); QCOMPARE(job->exec(), expectedSuccess); if (expectedSuccess) { const QString destFile = destDir + '/' + expectedFileName; QVERIFY2(QFile::exists(destFile), qPrintable(expectedFileName)); if (isDir) { QVERIFY(QFileInfo(destFile).isDir()); } else { QVERIFY(QFileInfo(destFile).isFile()); QFile file(destFile); QVERIFY(file.open(QIODevice::ReadOnly)); QCOMPARE(QString(file.readAll()), QString("Hello world")); } if (cut) { QVERIFY(!QFile::exists(urls.first().toLocalFile())); } else { QVERIFY(QFile::exists(urls.first().toLocalFile())); } QCOMPARE(spy.count(), isFile || cut ? 1 : 2); QCOMPARE(spy.at(0).at(0).value<QUrl>().toLocalFile(), destFile); } }
void TestBuddies::testSplitViewBuddies() { Sublime::MainWindow *pMainWindow = toSublimeWindow(m_uiController->activeMainWindow()); enableBuddies(); enableOpenAfterCurrent(); QTemporaryDir tempDirA; QDir dirA(tempDirA.path()); createFile(dirA, "classA.cpp"); createFile(dirA, "classA.h"); Sublime::Area *pCodeArea = m_uiController->activeArea(); QVERIFY(pCodeArea); IDocument *pClassAHeader = m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("classA.h"))); QVERIFY(pClassAHeader); pMainWindow->activeView()->setObjectName("classA.h"); // now, create a splitted view of the active view (pClassAHeader) Sublime::View *pNewView = pMainWindow->activeView()->document()->createView(); pNewView->setObjectName("splitOf" + pMainWindow->activeView()->objectName()); pCodeArea->addView(pNewView, pMainWindow->activeView(), Qt::Vertical); // and activate it pMainWindow->activateView(pNewView); // get the current view's container from the mainwindow QWidget *pCentral = pMainWindow->centralWidget(); QVERIFY(pCentral); QVERIFY(pCentral->inherits("QWidget")); QWidget *pSplitter = pCentral->findChild<QSplitter*>(); QVERIFY(pSplitter); QVERIFY(pSplitter->inherits("QSplitter")); Sublime::Container *pContainer = pSplitter->findChild<Sublime::Container*>(); QVERIFY(pContainer); // check that it only contains pNewView QVERIFY(pContainer->count() == 1 && pContainer->hasWidget(pNewView->widget())); // now open the correponding definition file, classA.cpp IDocument *pClassAImplem = m_documentController->openDocument(QUrl::fromLocalFile(dirA.filePath("classA.cpp"))); QVERIFY(pClassAImplem); pMainWindow->activeView()->setObjectName("classA.cpp"); // and check its presence alongside pNewView in pContainer QVERIFY(pContainer->hasWidget(pNewView->widget())); QVERIFY(pContainer->hasWidget(pMainWindow->activeView()->widget())); }
void tst_qmldiskcache::fileSelectors() { QQmlEngine engine; QTemporaryDir tempDir; QVERIFY(tempDir.isValid()); const QString testFilePath = tempDir.path() + "/test.qml"; { QFile f(testFilePath); QVERIFY2(f.open(QIODevice::WriteOnly), qPrintable(f.errorString())); f.write(QByteArrayLiteral("import QtQml 2.0\nQtObject { property int value: 42 }")); } const QString selector = QStringLiteral("testSelector"); const QString selectorPath = tempDir.path() + "/+" + selector; const QString selectedTestFilePath = selectorPath + "/test.qml"; { QVERIFY(QDir::root().mkpath(selectorPath)); QFile f(selectorPath + "/test.qml"); QVERIFY2(f.open(QIODevice::WriteOnly), qPrintable(f.errorString())); f.write(QByteArrayLiteral("import QtQml 2.0\nQtObject { property int value: 100 }")); } { QQmlComponent component(&engine, testFilePath); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); QCOMPARE(obj->property("value").toInt(), 42); QFile cacheFile(testFilePath + "c"); QVERIFY2(cacheFile.exists(), qPrintable(cacheFile.fileName())); } QQmlFileSelector qmlSelector(&engine); qmlSelector.setExtraSelectors(QStringList() << selector); engine.clearComponentCache(); { QQmlComponent component(&engine, testFilePath); QScopedPointer<QObject> obj(component.create()); QVERIFY(!obj.isNull()); QCOMPARE(obj->property("value").toInt(), 100); QFile cacheFile(selectedTestFilePath + "c"); QVERIFY2(cacheFile.exists(), qPrintable(cacheFile.fileName())); } }
QDir Project_sV::getDirectoryName() { QDir dirName; #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) //QTemporaryDir tempDir("slowmovideo"); QTemporaryDir tempDir;; // use default if (tempDir.isValid()) dirName = QDir(tempDir.path()); else #endif dirName = QDir::temp(); return dirName; }
void KInotifyTest::testFileClosedAfterWrite() { QTemporaryDir dir; touchFile(dir.path() + QLatin1String("/file")); KInotify kn(nullptr /*no config*/); kn.addWatch(dir.path(), KInotify::EventAll); QSignalSpy spy(&kn, SIGNAL(closedWrite(QString))); touchFile(dir.path() + QLatin1String("/file")); QVERIFY(spy.wait()); QCOMPARE(spy.count(), 1); QCOMPARE(spy.at(0).first().toString(), QString(dir.path() + QLatin1String("/file"))); }
void TemplateSelectionPagePrivate::previewTemplate(const QString& file) { SourceFileTemplate fileTemplate(file); if (!fileTemplate.isValid() || fileTemplate.outputFiles().isEmpty()) { return; } TemplatePreviewRenderer renderer; renderer.setEmptyLinesPolicy(TemplateRenderer::TrimEmptyLines); QTemporaryDir dir; QUrl base = QUrl::fromLocalFile(dir.path() + QLatin1Char('/')); QHash<QString, QUrl> fileUrls; foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) { QUrl url = base.resolved(QUrl(renderer.render(out.outputName))); fileUrls.insert(out.identifier, url); } DocumentChangeSet changes = renderer.renderFileTemplate(fileTemplate, base, fileUrls); changes.setActivationPolicy(DocumentChangeSet::DoNotActivate); changes.setUpdateHandling(DocumentChangeSet::NoUpdate); DocumentChangeSet::ChangeResult result = changes.applyAllChanges(); if (!result) { return; } int idx = 0; foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) { TemplatePreview* preview = nullptr; if (ui->tabWidget->count() > idx) { // reuse existing tab preview = qobject_cast<TemplatePreview*>(ui->tabWidget->widget(idx)); ui->tabWidget->setTabText(idx, out.label); Q_ASSERT(preview); } else { // create new tabs on demand preview = new TemplatePreview(page); ui->tabWidget->addTab(preview, out.label); } preview->document()->openUrl(fileUrls.value(out.identifier)); ++idx; } // remove superfluous tabs from last time while (ui->tabWidget->count() > fileUrls.size()) { delete ui->tabWidget->widget(fileUrls.size()); } return; }