cpptoolstestcase.cpp 13.9 KB
Newer Older
1 2
/****************************************************************************
**
Eike Ziller's avatar
Eike Ziller committed
3 4
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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
Eike Ziller's avatar
Eike Ziller committed
12 13
** a written agreement between you and The Qt Company.  For licensing terms and
** conditions see http://www.qt.io/terms-conditions.  For further information
Eike Ziller's avatar
Eike Ziller committed
14
** use the contact form at http://www.qt.io/contact-us.
15 16 17
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
Eike Ziller's avatar
Eike Ziller committed
18 19 20 21 22 23
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file.  Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
Eike Ziller's avatar
Eike Ziller committed
25 26
** In addition, as a special exception, The Qt Company gives you certain additional
** rights.  These rights are described in The Qt Company LGPL Exception
27 28 29 30 31
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "cpptoolstestcase.h"
32 33 34 35

#include "baseeditordocumentparser.h"
#include "baseeditordocumentprocessor.h"
#include "editordocumenthandle.h"
36
#include "cppmodelmanager.h"
37 38
#include "cppworkingcopy.h"

39
#include <coreplugin/editormanager/editormanager.h>
40
#include <projectexplorer/project.h>
41 42
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
43
#include <texteditor/texteditor.h>
44 45
#include <texteditor/codeassist/iassistproposal.h>
#include <texteditor/codeassist/iassistproposalmodel.h>
46 47

#include <cplusplus/CppDocument.h>
48
#include <utils/executeondestruction.h>
49 50 51 52
#include <utils/fileutils.h>

#include <QtTest>

53 54
using namespace ProjectExplorer;

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

63
static bool snapshotContains(const CPlusPlus::Snapshot &snapshot, const QSet<QString> &filePaths)
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
{
    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)
79 80 81
    : m_fileName(QString::fromUtf8(fileName))
    , m_source(QString::fromUtf8(source))
    , m_cursorMarker(cursorMarker)
82 83 84 85
{}

QString TestDocument::filePath() const
{
86 87 88
    if (!m_baseDirectory.isEmpty())
        return QDir::cleanPath(m_baseDirectory + QLatin1Char('/') + m_fileName);

89 90
    if (!QFileInfo(m_fileName).isAbsolute())
        return QDir::tempPath() + QLatin1Char('/') + m_fileName;
91

92
    return m_fileName;
93 94 95 96
}

bool TestDocument::writeToDisk() const
{
97
    return TestCase::writeFile(filePath(), m_source.toUtf8());
98 99 100
}

TestCase::TestCase(bool runGarbageCollector)
101
    : m_modelManager(CppModelManager::instance())
102
    , m_succeededSoFar(false)
103 104 105 106
    , m_runGarbageCollector(runGarbageCollector)
{
    if (m_runGarbageCollector)
        QVERIFY(garbageCollectGlobalSnapshot());
107
    m_succeededSoFar = true;
108 109 110 111
}

TestCase::~TestCase()
{
112
    QVERIFY(closeEditorsWithoutGarbageCollectorInvocation(m_editorsToClose));
113 114 115 116 117 118
    QCoreApplication::processEvents();

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

119 120 121 122 123
bool TestCase::succeededSoFar() const
{
    return m_succeededSoFar;
}

124 125 126 127 128 129 130 131 132 133 134 135
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;
}

136 137
CPlusPlus::Snapshot TestCase::globalSnapshot()
{
138
    return CppModelManager::instance()->snapshot();
139 140 141 142
}

bool TestCase::garbageCollectGlobalSnapshot()
{
143
    CppModelManager::instance()->GC();
144 145 146
    return globalSnapshot().isEmpty();
}

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
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);
}

172
bool TestCase::parseFiles(const QSet<QString> &filePaths)
173
{
174
    CppModelManager::instance()->updateSourceFiles(filePaths).waitForFinished();
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
    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)
{
190
    return parseFiles(QSet<QString>() << filePath);
191 192 193 194 195 196 197 198
}

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

199 200 201 202 203
bool TestCase::closeEditorWithoutGarbageCollectorInvocation(Core::IEditor *editor)
{
    return closeEditorsWithoutGarbageCollectorInvocation(QList<Core::IEditor *>() << editor);
}

204 205
CPlusPlus::Document::Ptr TestCase::waitForFileInGlobalSnapshot(const QString &filePath,
                                                               int timeOutInMs)
206
{
207 208
    const auto documents = waitForFilesInGlobalSnapshot(QStringList(filePath), timeOutInMs);
    return documents.isEmpty() ? CPlusPlus::Document::Ptr() : documents.first();
209 210
}

211 212
QList<CPlusPlus::Document::Ptr> TestCase::waitForFilesInGlobalSnapshot(const QStringList &filePaths,
                                                                       int timeOutInMs)
213
{
214 215 216
    QTime t;
    t.start();

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

232
bool TestCase::waitUntilCppModelManagerIsAwareOf(Project *project, int timeOutInMs)
233 234 235 236 237 238 239 240 241 242 243
{
    if (!project)
        return false;

    QTime t;
    t.start();

    CppModelManager *modelManager = CppModelManager::instance();
    forever {
        if (modelManager->projectInfo(project).isValid())
            return true;
244
        if (t.elapsed() > timeOutInMs)
245 246 247 248 249
            return false;
        QCoreApplication::processEvents();
    }
}

250 251 252 253 254 255 256 257 258 259 260
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;
}

261
ProjectOpenerAndCloser::ProjectOpenerAndCloser()
262 263 264 265 266 267
{
    QVERIFY(!SessionManager::hasProjects());
}

ProjectOpenerAndCloser::~ProjectOpenerAndCloser()
{
268 269 270 271 272 273 274 275 276 277
    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;
    });

278 279
    foreach (Project *project, m_openProjects)
        ProjectExplorerPlugin::unloadProject(project);
280

281 282 283 284
    QTime t;
    t.start();
    while (!hasGcFinished && t.elapsed() <= 30000)
        QCoreApplication::processEvents();
285 286
}

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

295
    Project *project = result.project();
296 297 298
    if (configureAsExampleProject)
        project->configureAsExampleProject(QStringList());

299 300
    if (TestCase::waitUntilCppModelManagerIsAwareOf(project)) {
        m_openProjects.append(project);
301
        return CppModelManager::instance()->projectInfo(project);
302
    }
303 304 305 306

    return ProjectInfo();
}

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

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;
}

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
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);
}

353
TemporaryCopiedDir::TemporaryCopiedDir(const QString &sourceDirPath)
354 355 356 357
{
    if (!m_isValid)
        return;

358 359
    if (sourceDirPath.isEmpty())
        return;
360

361 362 363 364 365 366 367 368 369 370
    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;
371 372 373 374 375 376 377 378
    }
}

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

379 380 381
FileWriterAndRemover::FileWriterAndRemover(const QString &filePath, const QByteArray &contents)
    : m_filePath(filePath)
{
382
    if (QFileInfo::exists(filePath)) {
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        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));
    }
}

402 403 404 405 406 407 408 409 410 411
IAssistProposalScopedPointer::IAssistProposalScopedPointer(TextEditor::IAssistProposal *proposal)
    : d(proposal)
{}

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

412 413 414 415 416 417 418 419 420 421 422
VerifyCleanCppModelManager::VerifyCleanCppModelManager()
{
    QVERIFY(isClean());
}

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

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

423
bool VerifyCleanCppModelManager::isClean(bool testOnlyForCleanedProjects)
424 425
{
    CppModelManager *mm = CppModelManager::instance();
426 427 428 429
    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());
430 431 432 433 434
    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()));
    }
435
    return true;
436 437
}

438 439
#undef RETURN_FALSE_IF_NOT

440 441
} // namespace Tests
} // namespace CppTools