cppmodelmanager_test.cpp 42.9 KB
Newer Older
1 2
/****************************************************************************
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 5 6 7 8 9 10 11 12
** Contact: http://www.qt-project.org/legal
**
** 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
** a written agreement between you and Digia.  For licensing terms and
Eike Ziller's avatar
Eike Ziller committed
13 14
** conditions see http://www.qt.io/licensing.  For further information
** 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 25 26 27 28 29 30
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

31
#include "builtineditordocumentparser.h"
32
#include "cppsourceprocessor.h"
33 34
#include "cpptoolsplugin.h"
#include "cpptoolstestcase.h"
35
#include "editordocumenthandle.h"
36 37
#include "modelmanagertesthelper.h"

38
#include <coreplugin/editormanager/editormanager.h>
39
#include <coreplugin/fileutils.h>
40
#include <coreplugin/testdatadir.h>
41 42
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/session.h>
43 44

#include <cplusplus/LookupContext.h>
45
#include <utils/hostosinfo.h>
46

47
#include <QDebug>
48
#include <QFileInfo>
49
#include <QTemporaryDir>
50
#include <QtTest>
51 52

using namespace CppTools::Internal;
hjk's avatar
hjk committed
53
using namespace ProjectExplorer;
54
using namespace CppTools;
55

56
typedef CPlusPlus::Document Document;
57

Orgad Shaneh's avatar
Orgad Shaneh committed
58
Q_DECLARE_METATYPE(QList<ProjectFile>)
59

60 61
namespace {

62 63
inline QString _(const QByteArray &ba) { return QString::fromLatin1(ba, ba.size()); }

64
class MyTestDataDir : public Core::Tests::TestDataDir
65
{
66
public:
67
    MyTestDataDir(const QString &dir)
68
        : TestDataDir(_(SRCDIR "/../../../tests/cppmodelmanager/") + dir)
69
    {}
70

71
    QString includeDir(bool cleaned = true) const
72
    { return directory(_("include"), cleaned); }
73 74

    QString frameworksDir(bool cleaned = true) const
75
    { return directory(_("frameworks"), cleaned); }
76 77

    QString fileFromSourcesDir(const QString &fileName) const
78
    { return directory(_("sources")) + fileName; }
79 80
};

81 82 83 84 85 86 87 88 89
// TODO: When possible, use this helper class in all tests
class ProjectCreator
{
public:
    ProjectCreator(ModelManagerTestHelper *modelManagerTestHelper)
        : modelManagerTestHelper(modelManagerTestHelper)
    {}

    /// 'files' is expected to be a list of file names that reside in 'dir'.
90
    void create(const QString &name, const QString &dir, const QStringList &files)
91
    {
92
        const MyTestDataDir projectDir(dir);
93 94 95 96
        foreach (const QString &file, files)
            projectFiles << projectDir.file(file);

        Project *project = modelManagerTestHelper->createProject(name);
97
        projectInfo = ProjectInfo(project);
98 99

        ProjectPart::Ptr part(new ProjectPart);
100
        part->languageVersion = ProjectPart::CXX14;
101 102 103 104 105
        part->qtVersion = ProjectPart::Qt5;
        foreach (const QString &file, projectFiles) {
            ProjectFile projectFile(file, ProjectFile::classify(file));
            part->files.append(projectFile);
        }
106
        projectInfo.appendProjectPart(part);
107
        projectInfo.finish();
108 109 110 111 112 113 114
    }

    ModelManagerTestHelper *modelManagerTestHelper;
    ProjectInfo projectInfo;
    QStringList projectFiles;
};

115 116 117 118 119 120 121
/// Open and configure given project as example project and remove
/// generated *.user file on destruction.
///
/// Requirement: No *.user file exists for the project.
class ExampleProjectConfigurator
{
public:
122
    ExampleProjectConfigurator(const QString &projectFile)
123
    {
124
        const QString projectUserFile = projectFile + _(".user");
125
        QVERIFY(!QFileInfo::exists(projectUserFile));
126 127 128

        // Open project
        QString errorOpeningProject;
129
        m_project = ProjectExplorerPlugin::openProject(projectFile, &errorOpeningProject);
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
        QVERIFY(m_project);
        QVERIFY(errorOpeningProject.isEmpty());

        // Configure project
        m_project->configureAsExampleProject(QStringList());

        m_fileToRemove = projectUserFile;
    }

    ~ExampleProjectConfigurator()
    {
        QVERIFY(!m_fileToRemove.isEmpty());
        QVERIFY(QFile::remove(m_fileToRemove));
    }

hjk's avatar
hjk committed
145
    Project *project() const
146 147 148 149 150
    {
        return m_project;
    }

private:
hjk's avatar
hjk committed
151
    Project *m_project;
152 153
    QString m_fileToRemove;
};
154

155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
/// Changes a file on the disk and restores its original contents on destruction
class FileChangerAndRestorer
{
public:
    FileChangerAndRestorer(const QString &filePath)
        : m_filePath(filePath)
    {
    }

    ~FileChangerAndRestorer()
    {
        restoreContents();
    }

    /// Saves the contents also internally so it can be restored on destruction
    bool readContents(QByteArray *contents)
    {
        Utils::FileReader fileReader;
        const bool isFetchOk = fileReader.fetch(m_filePath);
        if (isFetchOk) {
            m_originalFileContents = fileReader.data();
            if (contents)
                *contents = m_originalFileContents;
        }
        return isFetchOk;
    }

182
    bool writeContents(const QByteArray &contents) const
183
    {
184
        return CppTools::Tests::TestCase::writeFile(m_filePath, contents);
185 186 187 188 189
    }

private:
    void restoreContents() const
    {
190
        CppTools::Tests::TestCase::writeFile(m_filePath, m_originalFileContents);
191 192 193 194 195 196
    }

    QByteArray m_originalFileContents;
    const QString &m_filePath;
};

197
static QSet<QString> updateProjectInfo(CppModelManager *modelManager, ModelManagerTestHelper *helper,
198 199 200 201 202 203 204 205
                                     const ProjectInfo &projectInfo)
{
    helper->resetRefreshedSourceFiles();
    modelManager->updateProjectInfo(projectInfo).waitForFinished();
    QCoreApplication::processEvents();
    return helper->waitForRefreshedSourceFiles();
}

206 207
} // anonymous namespace

208 209
/// Check: The preprocessor cleans include and framework paths.
void CppToolsPlugin::test_modelmanager_paths_are_clean()
210 211 212 213
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

214
    const MyTestDataDir testDataDir(_("testdata"));
215

216
    Project *project = helper.createProject(_("test_modelmanager_paths_are_clean"));
217
    ProjectInfo pi = ProjectInfo(project);
218

219 220
    typedef ProjectPart::HeaderPath HeaderPath;

221
    ProjectPart::Ptr part(new ProjectPart);
222
    part->languageVersion = ProjectPart::CXX14;
223
    part->qtVersion = ProjectPart::Qt5;
224
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
225 226 227
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath)
            << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath);
228
    pi.appendProjectPart(part);
229
    pi.finish();
230 231 232

    mm->updateProjectInfo(pi);

233 234 235 236 237
    QList<HeaderPath> headerPaths = mm->headerPaths();
    QCOMPARE(headerPaths.size(), 2);
    QVERIFY(headerPaths.contains(HeaderPath(testDataDir.includeDir(), HeaderPath::IncludePath)));
    QVERIFY(headerPaths.contains(HeaderPath(testDataDir.frameworksDir(),
                                            HeaderPath::FrameworkPath)));
238
}
239

240
/// Check: Frameworks headers are resolved.
241 242
void CppToolsPlugin::test_modelmanager_framework_headers()
{
243
    if (Utils::HostOsInfo::isWindowsHost())
244
        QSKIP("Can't resolve framework soft links on Windows.");
245

246 247 248
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

249
    const MyTestDataDir testDataDir(_("testdata"));
250

251
    Project *project = helper.createProject(_("test_modelmanager_framework_headers"));
252
    ProjectInfo pi = ProjectInfo(project);
253

254 255
    typedef ProjectPart::HeaderPath HeaderPath;

256
    ProjectPart::Ptr part(new ProjectPart);
257
    part->languageVersion = ProjectPart::CXX14;
258
    part->qtVersion = ProjectPart::Qt5;
259
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
260 261 262
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath)
            << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath);
263
    const QString &source = testDataDir.fileFromSourcesDir(
264
        _("test_modelmanager_framework_headers.cpp"));
265
    part->files << ProjectFile(source, ProjectFile::CXXSource);
266
    pi.appendProjectPart(part);
267
    pi.finish();
268

269
    mm->updateProjectInfo(pi).waitForFinished();
270 271
    QCoreApplication::processEvents();

272
    QVERIFY(mm->snapshot().contains(source));
273
    Document::Ptr doc = mm->document(source);
274 275 276 277 278 279 280 281 282 283 284 285 286 287
    QVERIFY(!doc.isNull());
    CPlusPlus::Namespace *ns = doc->globalNamespace();
    QVERIFY(ns);
    QVERIFY(ns->memberCount() > 0);
    for (unsigned i = 0, ei = ns->memberCount(); i < ei; ++i) {
        CPlusPlus::Symbol *s = ns->memberAt(i);
        QVERIFY(s);
        QVERIFY(s->name());
        const CPlusPlus::Identifier *id = s->name()->asNameId();
        QVERIFY(id);
        QByteArray chars = id->chars();
        QVERIFY(chars.startsWith("success"));
    }
}
288 289

/// QTCREATORBUG-9056
290 291 292
/// Check: If the project configuration changes, all project files and their
///        includes have to be reparsed.
void CppToolsPlugin::test_modelmanager_refresh_also_includes_of_project_files()
293 294 295 296
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

297
    const MyTestDataDir testDataDir(_("testdata"));
298

299 300
    const QString testCpp(testDataDir.fileFromSourcesDir(_("test_modelmanager_refresh.cpp")));
    const QString testHeader(testDataDir.fileFromSourcesDir( _("test_modelmanager_refresh.h")));
301

302
    Project *project = helper.createProject(
303
                _("test_modelmanager_refresh_also_includes_of_project_files"));
304
    ProjectInfo pi = ProjectInfo(project);
305

306 307
    typedef ProjectPart::HeaderPath HeaderPath;

308
    ProjectPart::Ptr part(new ProjectPart);
309
    part->languageVersion = ProjectPart::CXX14;
310
    part->qtVersion = ProjectPart::Qt5;
311
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
312 313
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath);
314
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
315
    pi.appendProjectPart(part);
316
    pi.finish();
317

318
    QSet<QString> refreshedFiles = updateProjectInfo(mm, &helper, pi);
319 320 321 322 323 324
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    CPlusPlus::Snapshot snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));

325 326 327 328
    Document::Ptr headerDocumentBefore = snapshot.document(testHeader);
    const QList<CPlusPlus::Macro> macrosInHeaderBefore = headerDocumentBefore->definedMacros();
    QCOMPARE(macrosInHeaderBefore.size(), 1);
    QVERIFY(macrosInHeaderBefore.first().name() == "test_modelmanager_refresh_h");
329

330
    // Introduce a define that will enable another define once the document is reparsed.
331
    part->projectDefines = QByteArray("#define TEST_DEFINE 1\n");
332
    pi = ProjectInfo(project);
333
    pi.appendProjectPart(part);
334
    pi.finish();
335

336
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
337 338 339 340 341 342

    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));
343 344 345 346 347 348

    Document::Ptr headerDocumentAfter = snapshot.document(testHeader);
    const QList<CPlusPlus::Macro> macrosInHeaderAfter = headerDocumentAfter->definedMacros();
    QCOMPARE(macrosInHeaderAfter.size(), 2);
    QVERIFY(macrosInHeaderAfter.at(0).name() == "test_modelmanager_refresh_h");
    QVERIFY(macrosInHeaderAfter.at(1).name() == "TEST_DEFINE_DEFINED");
349
}
350 351

/// QTCREATORBUG-9205
352
/// Check: When reparsing the same files again, no errors occur
353
///        (The CppSourceProcessor's already seen files are properly cleared!).
354
void CppToolsPlugin::test_modelmanager_refresh_several_times()
355 356 357 358
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

359
    const MyTestDataDir testDataDir(_("testdata_refresh"));
360

361 362 363
    const QString testHeader1(testDataDir.file(_("defines.h")));
    const QString testHeader2(testDataDir.file(_("header.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
364

365
    Project *project = helper.createProject(_("test_modelmanager_refresh_several_times"));
366
    ProjectInfo pi = ProjectInfo(project);
367 368

    ProjectPart::Ptr part(new ProjectPart);
369
    part->languageVersion = ProjectPart::CXX14;
370 371 372 373
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
    part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
374
    pi.appendProjectPart(part);
375
    pi.finish();
376 377 378
    mm->updateProjectInfo(pi);

    CPlusPlus::Snapshot snapshot;
379
    QSet<QString> refreshedFiles;
380 381
    CPlusPlus::Document::Ptr document;

382
    QByteArray defines = "#define FIRST_DEFINE";
383
    for (int i = 0; i < 2; ++i) {
384
        pi = ProjectInfo(project);
385 386 387
        ProjectPart::Ptr part(new ProjectPart);
        // Simulate project configuration change by having different defines each time.
        defines += "\n#define ANOTHER_DEFINE";
388
        part->projectDefines = defines;
389
        part->languageVersion = ProjectPart::CXX14;
390 391 392 393 394
        part->qtVersion = ProjectPart::Qt5;
        part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
        part->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
        part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
        pi.appendProjectPart(part);
395
        pi.finish();
396

397
        refreshedFiles = updateProjectInfo(mm, &helper, pi);
398
        QCOMPARE(refreshedFiles.size(), 3);
399

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
        QVERIFY(refreshedFiles.contains(testHeader1));
        QVERIFY(refreshedFiles.contains(testHeader2));
        QVERIFY(refreshedFiles.contains(testCpp));

        snapshot = mm->snapshot();
        QVERIFY(snapshot.contains(testHeader1));
        QVERIFY(snapshot.contains(testHeader2));
        QVERIFY(snapshot.contains(testCpp));

        // No diagnostic messages expected
        document = snapshot.document(testHeader1);
        QVERIFY(document->diagnosticMessages().isEmpty());

        document = snapshot.document(testHeader2);
        QVERIFY(document->diagnosticMessages().isEmpty());

        document = snapshot.document(testCpp);
        QVERIFY(document->diagnosticMessages().isEmpty());
    }
}
420

421 422 423 424 425 426 427
/// QTCREATORBUG-9581
/// Check: If nothing has changes, nothing should be reindexed.
void CppToolsPlugin::test_modelmanager_refresh_test_for_changes()
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

428 429
    const MyTestDataDir testDataDir(_("testdata_refresh"));
    const QString testCpp(testDataDir.file(_("source.cpp")));
430

431
    Project *project = helper.createProject(_("test_modelmanager_refresh_2"));
432
    ProjectInfo pi = ProjectInfo(project);
433 434

    ProjectPart::Ptr part(new ProjectPart);
435
    part->languageVersion = ProjectPart::CXX14;
436 437 438
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    pi.appendProjectPart(part);
439
    pi.finish();
440 441

    // Reindexing triggers a reparsing thread
442
    helper.resetRefreshedSourceFiles();
443 444
    QFuture<void> firstFuture = mm->updateProjectInfo(pi);
    QVERIFY(firstFuture.isStarted() || firstFuture.isRunning());
445
    firstFuture.waitForFinished();
446
    const QSet<QString> refreshedFiles = helper.waitForRefreshedSourceFiles();
447 448 449 450 451 452 453 454
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));

    // No reindexing since nothing has changed
    QFuture<void> subsequentFuture = mm->updateProjectInfo(pi);
    QVERIFY(subsequentFuture.isCanceled() && subsequentFuture.isFinished());
}

455 456 457 458 459 460 461
/// Check: (1) Added project files are recognized and parsed.
/// Check: (2) Removed project files are recognized and purged from the snapshot.
void CppToolsPlugin::test_modelmanager_refresh_added_and_purge_removed()
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

462
    const MyTestDataDir testDataDir(_("testdata_refresh"));
463

464 465 466
    const QString testHeader1(testDataDir.file(_("header.h")));
    const QString testHeader2(testDataDir.file(_("defines.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
467

468
    Project *project = helper.createProject(_("test_modelmanager_refresh_3"));
469
    ProjectInfo pi = ProjectInfo(project);
470 471

    ProjectPart::Ptr part(new ProjectPart);
472
    part->languageVersion = ProjectPart::CXX14;
473 474 475 476
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
    pi.appendProjectPart(part);
477
    pi.finish();
478 479

    CPlusPlus::Snapshot snapshot;
480
    QSet<QString> refreshedFiles;
481

482
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
483 484 485 486 487 488 489 490 491 492

    QCOMPARE(refreshedFiles.size(), 2);
    QVERIFY(refreshedFiles.contains(testHeader1));
    QVERIFY(refreshedFiles.contains(testCpp));

    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader1));
    QVERIFY(snapshot.contains(testCpp));

    // Now add testHeader2 and remove testHeader1
493
    pi = ProjectInfo(project);
494
    ProjectPart::Ptr newPart(new ProjectPart);
495
    newPart->languageVersion = ProjectPart::CXX14;
496 497 498 499
    newPart->qtVersion = ProjectPart::Qt5;
    newPart->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    newPart->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
    pi.appendProjectPart(newPart);
500
    pi.finish();
501

502
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525

    // Only the added project file was reparsed
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testHeader2));

    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader2));
    QVERIFY(snapshot.contains(testCpp));
    // The removed project file is not anymore in the snapshot
    QVERIFY(!snapshot.contains(testHeader1));
}

/// Check: Timestamp modified files are reparsed if project files are added or removed
///        while the project configuration stays the same
void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change()
{
    QFETCH(QString, fileToChange);
    QFETCH(QList<ProjectFile>, initialProjectFiles);
    QFETCH(QList<ProjectFile>, finalProjectFiles);

    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

526
    Project *project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"));
527
    ProjectInfo pi = ProjectInfo(project);
528 529

    ProjectPart::Ptr part(new ProjectPart);
530
    part->languageVersion = ProjectPart::CXX14;
531 532 533
    part->qtVersion = ProjectPart::Qt5;
    foreach (const ProjectFile &file, initialProjectFiles)
        part->files.append(file);
534
    pi = ProjectInfo(project);
535
    pi.appendProjectPart(part);
536
    pi.finish();
537 538 539

    Document::Ptr document;
    CPlusPlus::Snapshot snapshot;
540
    QSet<QString> refreshedFiles;
541

542
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561

    QCOMPARE(refreshedFiles.size(), initialProjectFiles.size());
    snapshot = mm->snapshot();
    foreach (const ProjectFile &file, initialProjectFiles) {
        QVERIFY(refreshedFiles.contains(file.path));
        QVERIFY(snapshot.contains(file.path));
    }

    document = snapshot.document(fileToChange);
    const QDateTime lastModifiedBefore = document->lastModified();
    QCOMPARE(document->globalSymbolCount(), 1U);
    QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");

    // Modify the file
    QTest::qSleep(1000); // Make sure the timestamp is different
    FileChangerAndRestorer fileChangerAndRestorer(fileToChange);
    QByteArray originalContents;
    QVERIFY(fileChangerAndRestorer.readContents(&originalContents));
    const QByteArray newFileContentes = originalContents + "\nint addedOtherGlobal;";
562
    QVERIFY(fileChangerAndRestorer.writeContents(newFileContentes));
563 564 565 566 567

    // Add or remove source file. The configuration stays the same.
    part->files.clear();
    foreach (const ProjectFile &file, finalProjectFiles)
        part->files.append(file);
568
    pi = ProjectInfo(project);
569
    pi.appendProjectPart(part);
570
    pi.finish();
571

572
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593

    QCOMPARE(refreshedFiles.size(), finalProjectFiles.size());
    snapshot = mm->snapshot();
    foreach (const ProjectFile &file, finalProjectFiles) {
        QVERIFY(refreshedFiles.contains(file.path));
        QVERIFY(snapshot.contains(file.path));
    }
    document = snapshot.document(fileToChange);
    const QDateTime lastModifiedAfter = document->lastModified();
    QVERIFY(lastModifiedAfter > lastModifiedBefore);
    QCOMPARE(document->globalSymbolCount(), 2U);
    QCOMPARE(document->globalSymbolAt(0)->name()->identifier()->chars(), "someGlobal");
    QCOMPARE(document->globalSymbolAt(1)->name()->identifier()->chars(), "addedOtherGlobal");
}

void CppToolsPlugin::test_modelmanager_refresh_timeStampModified_if_sourcefiles_change_data()
{
    QTest::addColumn<QString>("fileToChange");
    QTest::addColumn<QList<ProjectFile> >("initialProjectFiles");
    QTest::addColumn<QList<ProjectFile> >("finalProjectFiles");

594 595 596
    const MyTestDataDir testDataDir(_("testdata_refresh2"));
    const QString testCpp(testDataDir.file(_("source.cpp")));
    const QString testCpp2(testDataDir.file(_("source2.cpp")));
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611

    const QString fileToChange = testCpp;
    QList<ProjectFile> projectFiles1 = QList<ProjectFile>()
        << ProjectFile(testCpp, ProjectFile::CXXSource);
    QList<ProjectFile> projectFiles2 = QList<ProjectFile>()
        << ProjectFile(testCpp, ProjectFile::CXXSource)
        << ProjectFile(testCpp2, ProjectFile::CXXSource);

    // Add a file
    QTest::newRow("case: add project file") << fileToChange << projectFiles1 << projectFiles2;

    // Remove a file
    QTest::newRow("case: remove project file") << fileToChange << projectFiles2 << projectFiles1;
}

612 613
/// Check: If a second project is opened, the code model is still aware of
///        files of the first project.
614 615
void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
{
616
    QSet<QString> refreshedFiles;
617 618 619 620 621 622
    ModelManagerTestHelper helper;
    ProjectCreator project1(&helper);
    ProjectCreator project2(&helper);
    CppModelManager *mm = CppModelManager::instance();

    // Project 1
623 624 625 626 627
    project1.create(_("test_modelmanager_snapshot_after_two_projects.1"),
                    _("testdata_project1"),
                    QStringList() << _("foo.h")
                                  << _("foo.cpp")
                                  << _("main.cpp"));
628

629
    refreshedFiles = updateProjectInfo(mm, &helper, project1.projectInfo);
630
    QCOMPARE(refreshedFiles, project1.projectFiles.toSet());
631 632 633 634 635 636
    const int snapshotSizeAfterProject1 = mm->snapshot().size();

    foreach (const QString &file, project1.projectFiles)
        QVERIFY(mm->snapshot().contains(file));

    // Project 2
637 638 639 640 641
    project2.create(_("test_modelmanager_snapshot_after_two_projects.2"),
                    _("testdata_project2"),
                    QStringList() << _("bar.h")
                                  << _("bar.cpp")
                                  << _("main.cpp"));
642

643
    refreshedFiles = updateProjectInfo(mm, &helper, project2.projectInfo);
644
    QCOMPARE(refreshedFiles, project2.projectFiles.toSet());
645 646 647 648 649 650 651 652 653 654

    const int snapshotSizeAfterProject2 = mm->snapshot().size();
    QVERIFY(snapshotSizeAfterProject2 > snapshotSizeAfterProject1);
    QVERIFY(snapshotSizeAfterProject2 >= snapshotSizeAfterProject1 + project2.projectFiles.size());

    foreach (const QString &file, project1.projectFiles)
        QVERIFY(mm->snapshot().contains(file));
    foreach (const QString &file, project2.projectFiles)
        QVERIFY(mm->snapshot().contains(file));
}
655

656 657
/// Check: (1) For a project with a *.ui file an AbstractEditorSupport object
///            is added for the ui_* file.
658
/// Check: (2) The CppSourceProcessor can successfully resolve the ui_* file
659
///            though it might not be actually generated in the build dir.
660 661
void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
{
662 663
    ModelManagerTestHelper helper;

664 665
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString projectFile = testDataDirectory.file(_("testdata_guiproject1.pro"));
666 667

    // Open project with *.ui file
668
    ExampleProjectConfigurator exampleProjectConfigurator(projectFile);
669
    Project *project = exampleProjectConfigurator.project();
670 671 672

    // Check working copy.
    // An AbstractEditorSupport object should have been added for the ui_* file.
673
    CppModelManager *mm = CppModelManager::instance();
674
    WorkingCopy workingCopy = mm->workingCopy();
675 676 677 678

    QCOMPARE(workingCopy.size(), 2); // mm->configurationFileName() and "ui_*.h"

    QStringList fileNamesInWorkinCopy;
679
    QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
680 681
    while (it.hasNext()) {
        it.next();
682
        fileNamesInWorkinCopy << QFileInfo(it.key().toString()).fileName();
683 684
    }
    fileNamesInWorkinCopy.sort();
685
    const QString expectedUiHeaderFileName = _("ui_mainwindow.h");
686 687 688
    QCOMPARE(fileNamesInWorkinCopy.at(0), mm->configurationFileName());
    QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName);

689 690
    // Check CppSourceProcessor / includes.
    // The CppSourceProcessor is expected to find the ui_* file in the working copy.
691
    const QString fileIncludingTheUiFile = testDataDirectory.file(_("mainwindow.cpp"));
692 693 694 695 696 697 698 699
    while (!mm->snapshot().document(fileIncludingTheUiFile))
        QCoreApplication::processEvents();

    const CPlusPlus::Snapshot snapshot = mm->snapshot();
    const Document::Ptr document = snapshot.document(fileIncludingTheUiFile);
    QVERIFY(document);
    const QStringList includedFiles = document->includedFiles();
    QCOMPARE(includedFiles.size(), 2);
700 701
    QCOMPARE(QFileInfo(includedFiles.at(0)).fileName(), _("mainwindow.h"));
    QCOMPARE(QFileInfo(includedFiles.at(1)).fileName(), _("ui_mainwindow.h"));
702 703

    // Close Project
hjk's avatar
hjk committed
704
    SessionManager::removeProject(project);
705
    helper.waitForFinishedGc();
706
}
707 708 709 710 711

/// QTCREATORBUG-9828: Locator shows symbols of closed files
/// Check: The garbage collector should be run if the last CppEditor is closed.
void CppToolsPlugin::test_modelmanager_gc_if_last_cppeditor_closed()
{
712 713
    ModelManagerTestHelper helper;

714 715
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString file = testDataDirectory.file(_("main.cpp"));
716 717

    CppModelManager *mm = CppModelManager::instance();
718
    helper.resetRefreshedSourceFiles();
719 720

    // Open a file in the editor
hjk's avatar
hjk committed
721
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
722
    Core::IEditor *editor = Core::EditorManager::openEditor(file);
723
    QVERIFY(editor);
hjk's avatar
hjk committed
724
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
725 726 727
    QVERIFY(mm->isCppEditor(editor));
    QVERIFY(mm->workingCopy().contains(file));

728 729
    // Wait until the file is refreshed
    helper.waitForRefreshedSourceFiles();
730 731

    // Close file/editor
732
    Core::EditorManager::closeDocument(editor->document(), /*askAboutModifiedEditors=*/ false);
733
    helper.waitForFinishedGc();
734 735 736 737 738

    // Check: File is removed from the snapshpt
    QVERIFY(!mm->workingCopy().contains(file));
    QVERIFY(!mm->snapshot().contains(file));
}
739 740 741 742 743 744

/// Check: Files that are open in the editor are not garbage collected.
void CppToolsPlugin::test_modelmanager_dont_gc_opened_files()
{
    ModelManagerTestHelper helper;

745 746
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString file = testDataDirectory.file(_("main.cpp"));
747 748

    CppModelManager *mm = CppModelManager::instance();
749
    helper.resetRefreshedSourceFiles();
750 751

    // Open a file in the editor
hjk's avatar
hjk committed
752
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
753
    Core::IEditor *editor = Core::EditorManager::openEditor(file);
754
    QVERIFY(editor);
hjk's avatar
hjk committed
755
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
756 757
    QVERIFY(mm->isCppEditor(editor));

758 759
    // Wait until the file is refreshed and check whether it is in the working copy
    helper.waitForRefreshedSourceFiles();
760

761 762 763 764 765 766 767 768 769 770
    QVERIFY(mm->workingCopy().contains(file));

    // Run the garbage collector
    mm->GC();

    // Check: File is still there
    QVERIFY(mm->workingCopy().contains(file));
    QVERIFY(mm->snapshot().contains(file));

    // Close editor
771
    Core::EditorManager::closeDocument(editor->document());
772 773 774
    helper.waitForFinishedGc();
    QVERIFY(mm->snapshot().isEmpty());
}
775 776 777 778 779 780 781

namespace {
struct EditorCloser {
    Core::IEditor *editor;
    EditorCloser(Core::IEditor *editor): editor(editor) {}
    ~EditorCloser()
    {
782
        using namespace CppTools;
783
        if (editor)
784
            QVERIFY(Tests::TestCase::closeEditorWithoutGarbageCollectorInvocation(editor));
785 786
    }
};
787 788 789 790 791 792 793 794

QString nameOfFirstDeclaration(const Document::Ptr &doc)
{
    if (doc && doc->globalNamespace()) {
        if (CPlusPlus::Symbol *s = doc->globalSymbolAt(0)) {
            if (CPlusPlus::Declaration *decl = s->asDeclaration()) {
                if (const CPlusPlus::Name *name = decl->name()) {
                    if (const CPlusPlus::Identifier *identifier = name->identifier())
795
                        return QString::fromUtf8(identifier->chars(), identifier->size());
796 797 798 799 800 801
                }
            }
        }
    }
    return QString();
}
802 803 804 805 806 807
}

void CppToolsPlugin::test_modelmanager_defines_per_project()
{
    ModelManagerTestHelper helper;

808 809 810 811
    MyTestDataDir testDataDirectory(_("testdata_defines"));
    const QString main1File = testDataDirectory.file(_("main1.cpp"));
    const QString main2File = testDataDirectory.file(_("main2.cpp"));
    const QString header = testDataDirectory.file(_("header.h"));
812 813 814

    CppModelManager *mm = CppModelManager::instance();

815
    Project *project = helper.createProject(_("test_modelmanager_defines_per_project"));
816

817 818
    typedef ProjectPart::HeaderPath HeaderPath;

819
    ProjectPart::Ptr part1(new ProjectPart);
820
    part1->projectFile = QLatin1String("project1.projectfile");
821 822
    part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource));
    part1->files.append(ProjectFile(header, ProjectFile::CXXHeader));
823
    part1->languageVersion = ProjectPart::CXX11;
824
    part1->qtVersion = ProjectPart::NoQt;
825
    part1->projectDefines = QByteArray("#define SUB1\n");
826 827
    part1->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
828 829

    ProjectPart::Ptr part2(new ProjectPart);
830
    part2->projectFile = QLatin1String("project1.projectfile");
831 832
    part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource));
    part2->files.append(ProjectFile(header, ProjectFile::CXXHeader));
833
    part2->languageVersion = ProjectPart::CXX11;
834
    part2->qtVersion = ProjectPart::NoQt;
835
    part2->projectDefines = QByteArray("#define SUB2\n");
836 837
    part2->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
838

839
    ProjectInfo pi = ProjectInfo(project);
840 841
    pi.appendProjectPart(part1);
    pi.appendProjectPart(part2);
842
    pi.finish();
843

844
    updateProjectInfo(mm, &helper, pi);
845 846 847
    QCOMPARE(mm->snapshot().size(), 4);

    // Open a file in the editor
hjk's avatar
hjk committed
848
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
849

850 851 852 853 854 855 856 857 858 859 860 861 862
    struct Data {
        QString firstDeclarationName;
        QString fileName;
    } d[] = {
        { _("one"), main1File },
        { _("two"), main2File }
    };
    const int size = sizeof(d) / sizeof(d[0]);
    for (int i = 0; i < size; ++i) {
        const QString firstDeclarationName = d[i].firstDeclarationName;
        const QString fileName = d[i].fileName;

        Core::IEditor *editor = Core::EditorManager::openEditor(fileName);
863 864
        EditorCloser closer(editor);
        QVERIFY(editor);
hjk's avatar
hjk committed
865
        QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
866 867
        QVERIFY(mm->isCppEditor(editor));

868
        Document::Ptr doc = mm->document(fileName);
869
        QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName);
870 871
    }
}
872