cpptoolstestcase.cpp 13.6 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 24 25 26
**
****************************************************************************/

#include "cpptoolstestcase.h"
27 28 29 30

#include "baseeditordocumentparser.h"
#include "baseeditordocumentprocessor.h"
#include "editordocumenthandle.h"
31
#include "cppmodelmanager.h"
32
#include "cppworkingcopy.h"
33
#include "projectinfo.h"
34

35
#include <coreplugin/editormanager/editormanager.h>
36
#include <projectexplorer/project.h>
37 38
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
39
#include <texteditor/texteditor.h>
40 41
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/codeassist/iassistproposalmodel.h>
42 43

#include <cplusplus/CppDocument.h>
44
#include <utils/executeondestruction.h>
45 46 47 48
#include <utils/fileutils.h>

#include <QtTest>

49 50
using namespace ProjectExplorer;

51 52
static bool closeEditorsWithoutGarbageCollectorInvocation(const QList<Core::IEditor *> &editors)
{
53
    CppTools::CppModelManager::instance()->enableGarbageCollector(false);
54
    const bool closeEditorsSucceeded = Core::EditorManager::closeEditors(editors, false);
55
    CppTools::CppModelManager::instance()->enableGarbageCollector(true);
56 57 58
    return closeEditorsSucceeded;
}

59
static bool snapshotContains(const CPlusPlus::Snapshot &snapshot, const QSet<QString> &filePaths)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
{
    foreach (const QString &filePath, filePaths) {
        if (!snapshot.contains(filePath)) {
            const QString warning = QLatin1String("Missing file in snapshot: ") + filePath;
            QWARN(qPrintable(warning));
            return false;
        }
    }
    return true;
}

namespace CppTools {
namespace Tests {

TestDocument::TestDocument(const QByteArray &fileName, const QByteArray &source, char cursorMarker)
75 76 77
    : m_fileName(QString::fromUtf8(fileName))
    , m_source(QString::fromUtf8(source))
    , m_cursorMarker(cursorMarker)
78 79 80 81
{}

QString TestDocument::filePath() const
{
82 83 84
    if (!m_baseDirectory.isEmpty())
        return QDir::cleanPath(m_baseDirectory + QLatin1Char('/') + m_fileName);

85 86
    if (!QFileInfo(m_fileName).isAbsolute())
        return QDir::tempPath() + QLatin1Char('/') + m_fileName;
87

88
    return m_fileName;
89 90 91 92
}

bool TestDocument::writeToDisk() const
{
93
    return TestCase::writeFile(filePath(), m_source.toUtf8());
94 95 96
}

TestCase::TestCase(bool runGarbageCollector)
97
    : m_modelManager(CppModelManager::instance())
98
    , m_succeededSoFar(false)
99 100 101 102
    , m_runGarbageCollector(runGarbageCollector)
{
    if (m_runGarbageCollector)
        QVERIFY(garbageCollectGlobalSnapshot());
103
    m_succeededSoFar = true;
104 105 106 107
}

TestCase::~TestCase()
{
108
    QVERIFY(closeEditorsWithoutGarbageCollectorInvocation(m_editorsToClose));
109 110 111 112 113 114
    QCoreApplication::processEvents();

    if (m_runGarbageCollector)
        QVERIFY(garbageCollectGlobalSnapshot());
}

115 116 117 118 119
bool TestCase::succeededSoFar() const
{
    return m_succeededSoFar;
}

120 121 122 123 124 125 126 127 128 129 130 131
bool TestCase::openBaseTextEditor(const QString &fileName, TextEditor::BaseTextEditor **editor)
{
    typedef TextEditor::BaseTextEditor BTEditor;
    if (BTEditor *e = qobject_cast<BTEditor *>(Core::EditorManager::openEditor(fileName))) {
        if (editor) {
            *editor = e;
            return true;
        }
    }
    return false;
}

132 133
CPlusPlus::Snapshot TestCase::globalSnapshot()
{
134
    return CppModelManager::instance()->snapshot();
135 136 137 138
}

bool TestCase::garbageCollectGlobalSnapshot()
{
139
    CppModelManager::instance()->GC();
140 141 142
    return globalSnapshot().isEmpty();
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
static bool waitForProcessedEditorDocument_internal(CppEditorDocumentHandle *editorDocument,
                                                    int timeOutInMs)
{
    QTC_ASSERT(editorDocument, return false);

    QTime timer;
    timer.start();

    forever {
        if (!editorDocument->processor()->isParserRunning())
            return true;
        if (timer.elapsed() > timeOutInMs)
            return false;

        QCoreApplication::processEvents();
        QThread::msleep(20);
    }
}

bool TestCase::waitForProcessedEditorDocument(const QString &filePath, int timeOutInMs)
{
    auto *editorDocument = CppModelManager::instance()->cppEditorDocument(filePath);
    return waitForProcessedEditorDocument_internal(editorDocument, timeOutInMs);
}

168
bool TestCase::parseFiles(const QSet<QString> &filePaths)
169
{
170
    CppModelManager::instance()->updateSourceFiles(filePaths).waitForFinished();
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    QCoreApplication::processEvents();
    const CPlusPlus::Snapshot snapshot = globalSnapshot();
    if (snapshot.isEmpty()) {
        QWARN("After parsing: snapshot is empty.");
        return false;
    }
    if (!snapshotContains(snapshot, filePaths)) {
        QWARN("After parsing: snapshot does not contain all expected files.");
        return false;
    }
    return true;
}

bool TestCase::parseFiles(const QString &filePath)
{
186
    return parseFiles(QSet<QString>() << filePath);
187 188 189 190 191 192 193 194
}

void TestCase::closeEditorAtEndOfTestCase(Core::IEditor *editor)
{
    if (editor && !m_editorsToClose.contains(editor))
        m_editorsToClose.append(editor);
}

195 196 197 198 199
bool TestCase::closeEditorWithoutGarbageCollectorInvocation(Core::IEditor *editor)
{
    return closeEditorsWithoutGarbageCollectorInvocation(QList<Core::IEditor *>() << editor);
}

200 201
CPlusPlus::Document::Ptr TestCase::waitForFileInGlobalSnapshot(const QString &filePath,
                                                               int timeOutInMs)
202
{
203 204
    const auto documents = waitForFilesInGlobalSnapshot(QStringList(filePath), timeOutInMs);
    return documents.isEmpty() ? CPlusPlus::Document::Ptr() : documents.first();
205 206
}

207 208
QList<CPlusPlus::Document::Ptr> TestCase::waitForFilesInGlobalSnapshot(const QStringList &filePaths,
                                                                       int timeOutInMs)
209
{
210 211 212
    QTime t;
    t.start();

213 214 215 216 217 218 219
    QList<CPlusPlus::Document::Ptr> result;
    foreach (const QString &filePath, filePaths) {
        forever {
            if (CPlusPlus::Document::Ptr document = globalSnapshot().document(filePath)) {
                result.append(document);
                break;
            }
220 221
            if (t.elapsed() > timeOutInMs)
                return QList<CPlusPlus::Document::Ptr>();
222 223 224 225 226 227
            QCoreApplication::processEvents();
        }
    }
    return result;
}

228
bool TestCase::waitUntilCppModelManagerIsAwareOf(Project *project, int timeOutInMs)
229 230 231 232 233 234 235 236 237 238 239
{
    if (!project)
        return false;

    QTime t;
    t.start();

    CppModelManager *modelManager = CppModelManager::instance();
    forever {
        if (modelManager->projectInfo(project).isValid())
            return true;
240
        if (t.elapsed() > timeOutInMs)
241 242 243 244 245
            return false;
        QCoreApplication::processEvents();
    }
}

246 247 248 249 250 251 252 253 254 255 256
bool TestCase::writeFile(const QString &filePath, const QByteArray &contents)
{
    Utils::FileSaver saver(filePath);
    if (!saver.write(contents) || !saver.finalize()) {
        const QString warning = QLatin1String("Failed to write file to disk: ") + filePath;
        QWARN(qPrintable(warning));
        return false;
    }
    return true;
}

257
ProjectOpenerAndCloser::ProjectOpenerAndCloser()
258 259 260 261 262 263
{
    QVERIFY(!SessionManager::hasProjects());
}

ProjectOpenerAndCloser::~ProjectOpenerAndCloser()
{
264 265 266 267 268 269 270 271 272 273
    if (m_openProjects.isEmpty())
        return;

    bool hasGcFinished = false;
    QMetaObject::Connection connection;
    Utils::ExecuteOnDestruction disconnect([&]() { QObject::disconnect(connection); });
    connection = QObject::connect(CppModelManager::instance(), &CppModelManager::gcFinished, [&]() {
        hasGcFinished = true;
    });

274 275
    foreach (Project *project, m_openProjects)
        ProjectExplorerPlugin::unloadProject(project);
276

277 278 279 280
    QTime t;
    t.start();
    while (!hasGcFinished && t.elapsed() <= 30000)
        QCoreApplication::processEvents();
281 282
}

283
ProjectInfo ProjectOpenerAndCloser::open(const QString &projectFile, bool configureAsExampleProject)
284
{
285 286 287
    ProjectExplorerPlugin::OpenProjectResult result = ProjectExplorerPlugin::openProject(projectFile);
    if (!result) {
        qWarning() << result.errorMessage() << result.alreadyOpen();
288
        return ProjectInfo();
289
    }
290

291
    Project *project = result.project();
292
    if (configureAsExampleProject)
293
        project->configureAsExampleProject({ });
294

295 296
    if (TestCase::waitUntilCppModelManagerIsAwareOf(project)) {
        m_openProjects.append(project);
297
        return CppModelManager::instance()->projectInfo(project);
298
    }
299 300 301 302

    return ProjectInfo();
}

303
TemporaryDir::TemporaryDir()
304 305
    : m_temporaryDir(QFileInfo(QDir::tempPath()).canonicalFilePath()
                        + QLatin1String("/qtcreator-tests-XXXXXX"))
306
    , m_isValid(m_temporaryDir.isValid())
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
{
}

QString TemporaryDir::createFile(const QByteArray &relativePath, const QByteArray &contents)
{
    const QString relativePathString = QString::fromUtf8(relativePath);
    if (relativePathString.isEmpty() || QFileInfo(relativePathString).isAbsolute())
        return QString();

    const QString filePath = m_temporaryDir.path() + QLatin1Char('/') + relativePathString;
    if (!TestCase::writeFile(filePath, contents))
        return QString();
    return filePath;
}

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
static bool copyRecursively(const QString &sourceDirPath,
                            const QString &targetDirPath,
                            QString *error)
{
    auto copyHelper = [](QFileInfo sourceInfo, QFileInfo targetInfo, QString *error) -> bool {
        const QString sourcePath = sourceInfo.absoluteFilePath();
        const QString targetPath = targetInfo.absoluteFilePath();
        if (!QFile::copy(sourcePath, targetPath)) {
            if (error) {
                *error = QString::fromLatin1("copyRecursively() failed: \"%1\" to \"%2\".")
                            .arg(sourcePath, targetPath);
            }
            return false;
        }

        // Copied files from Qt resources are read-only. Make them writable
        // so that their parent directory can be removed without warnings.
        QFile file(targetPath);
        return file.setPermissions(file.permissions() | QFile::WriteUser);
    };

    return Utils::FileUtils::copyRecursively(Utils::FileName::fromString(sourceDirPath),
                                             Utils::FileName::fromString(targetDirPath),
                                             error,
                                             copyHelper);
}

349
TemporaryCopiedDir::TemporaryCopiedDir(const QString &sourceDirPath)
350 351 352 353
{
    if (!m_isValid)
        return;

354 355
    if (sourceDirPath.isEmpty())
        return;
356

357 358 359 360 361 362 363 364 365 366
    QFileInfo fi(sourceDirPath);
    if (!fi.exists() || !fi.isReadable()) {
        m_isValid = false;
        return;
    }

    QString errorMessage;
    if (!copyRecursively(sourceDirPath, path(), &errorMessage)) {
        QWARN(qPrintable(errorMessage));
        m_isValid = false;
367 368 369 370 371 372 373 374
    }
}

QString TemporaryCopiedDir::absolutePath(const QByteArray &relativePath) const
{
    return m_temporaryDir.path() + QLatin1Char('/') + QString::fromUtf8(relativePath);
}

375 376 377
FileWriterAndRemover::FileWriterAndRemover(const QString &filePath, const QByteArray &contents)
    : m_filePath(filePath)
{
378
    if (QFileInfo::exists(filePath)) {
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
        const QString warning = QString::fromLatin1(
            "Will not overwrite existing file: \"%1\"."
            " If this file is left over due to a(n) abort/crash, please remove manually.")
                .arg(m_filePath);
        QWARN(qPrintable(warning));
        m_writtenSuccessfully = false;
    } else {
        m_writtenSuccessfully = TestCase::writeFile(filePath, contents);
    }
}

FileWriterAndRemover::~FileWriterAndRemover()
{
    if (m_writtenSuccessfully && !QFile::remove(m_filePath)) {
        const QString warning = QLatin1String("Failed to remove file from disk: ") + m_filePath;
        QWARN(qPrintable(warning));
    }
}

398 399 400 401 402 403 404 405 406 407
IAssistProposalScopedPointer::IAssistProposalScopedPointer(TextEditor::IAssistProposal *proposal)
    : d(proposal)
{}

IAssistProposalScopedPointer::~IAssistProposalScopedPointer()
{
    if (d && d->model())
        delete d->model();
}

408 409 410 411 412 413 414 415 416 417 418
VerifyCleanCppModelManager::VerifyCleanCppModelManager()
{
    QVERIFY(isClean());
}

VerifyCleanCppModelManager::~VerifyCleanCppModelManager() {
    QVERIFY(isClean());
}

#define RETURN_FALSE_IF_NOT(check) if (!(check)) return false;

419
bool VerifyCleanCppModelManager::isClean(bool testOnlyForCleanedProjects)
420 421
{
    CppModelManager *mm = CppModelManager::instance();
422 423 424 425
    RETURN_FALSE_IF_NOT(mm->projectInfos().isEmpty());
    RETURN_FALSE_IF_NOT(mm->headerPaths().isEmpty());
    RETURN_FALSE_IF_NOT(mm->definedMacros().isEmpty());
    RETURN_FALSE_IF_NOT(mm->projectFiles().isEmpty());
426 427 428 429 430
    if (!testOnlyForCleanedProjects) {
        RETURN_FALSE_IF_NOT(mm->snapshot().isEmpty());
        RETURN_FALSE_IF_NOT(mm->workingCopy().size() == 1);
        RETURN_FALSE_IF_NOT(mm->workingCopy().contains(mm->configurationFileName()));
    }
431
    return true;
432 433
}

434 435
#undef RETURN_FALSE_IF_NOT

436 437
} // namespace Tests
} // namespace CppTools