cppmodelmanager_test.cpp 42.4 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 <QtTest>
49

50
using namespace CppTools;
51
using namespace CppTools::Internal;
52
using namespace CppTools::Tests;
hjk's avatar
hjk committed
53
using namespace ProjectExplorer;
54

55
typedef CPlusPlus::Document Document;
56

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

59 60
namespace {

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

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

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

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

    QString fileFromSourcesDir(const QString &fileName) const
77
    { return directory(_("sources")) + QLatin1Char('/') + fileName; }
78 79
};

80 81 82 83 84 85 86 87 88
QStringList toAbsolutePaths(const QStringList &relativePathList,
                            const Tests::TemporaryCopiedDir &temporaryDir)
{
    QStringList result;
    foreach (const QString &file, relativePathList)
        result << temporaryDir.absolutePath(file.toUtf8());
    return result;
}

89 90 91 92 93 94 95 96 97
// 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'.
98
    void create(const QString &name, const QString &dir, const QStringList &files)
99
    {
100
        const MyTestDataDir projectDir(dir);
101 102 103 104
        foreach (const QString &file, files)
            projectFiles << projectDir.file(file);

        Project *project = modelManagerTestHelper->createProject(name);
105
        projectInfo = ProjectInfo(project);
106 107

        ProjectPart::Ptr part(new ProjectPart);
108
        part->languageVersion = ProjectPart::CXX14;
109 110 111 112 113
        part->qtVersion = ProjectPart::Qt5;
        foreach (const QString &file, projectFiles) {
            ProjectFile projectFile(file, ProjectFile::classify(file));
            part->files.append(projectFile);
        }
114
        projectInfo.appendProjectPart(part);
115
        projectInfo.finish();
116 117 118 119 120 121 122
    }

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

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
/// 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;
    }

150
    bool writeContents(const QByteArray &contents) const
151
    {
152
        return TestCase::writeFile(m_filePath, contents);
153 154 155 156 157
    }

private:
    void restoreContents() const
    {
158
        TestCase::writeFile(m_filePath, m_originalFileContents);
159 160 161 162 163 164
    }

    QByteArray m_originalFileContents;
    const QString &m_filePath;
};

165
static QSet<QString> updateProjectInfo(CppModelManager *modelManager, ModelManagerTestHelper *helper,
166 167 168 169 170 171 172 173
                                     const ProjectInfo &projectInfo)
{
    helper->resetRefreshedSourceFiles();
    modelManager->updateProjectInfo(projectInfo).waitForFinished();
    QCoreApplication::processEvents();
    return helper->waitForRefreshedSourceFiles();
}

174 175
} // anonymous namespace

176 177
/// Check: The preprocessor cleans include and framework paths.
void CppToolsPlugin::test_modelmanager_paths_are_clean()
178 179 180 181
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

182
    const MyTestDataDir testDataDir(_("testdata"));
183

184
    Project *project = helper.createProject(_("test_modelmanager_paths_are_clean"));
185
    ProjectInfo pi = ProjectInfo(project);
186

187 188
    typedef ProjectPart::HeaderPath HeaderPath;

189
    ProjectPart::Ptr part(new ProjectPart);
190
    part->languageVersion = ProjectPart::CXX14;
191
    part->qtVersion = ProjectPart::Qt5;
192
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
193 194 195
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath)
            << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath);
196
    pi.appendProjectPart(part);
197
    pi.finish();
198 199 200

    mm->updateProjectInfo(pi);

201 202 203 204 205
    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)));
206
}
207

208
/// Check: Frameworks headers are resolved.
209 210
void CppToolsPlugin::test_modelmanager_framework_headers()
{
211
    if (Utils::HostOsInfo::isWindowsHost())
212
        QSKIP("Can't resolve framework soft links on Windows.");
213

214 215 216
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

217
    const MyTestDataDir testDataDir(_("testdata"));
218

219
    Project *project = helper.createProject(_("test_modelmanager_framework_headers"));
220
    ProjectInfo pi = ProjectInfo(project);
221

222 223
    typedef ProjectPart::HeaderPath HeaderPath;

224
    ProjectPart::Ptr part(new ProjectPart);
225
    part->languageVersion = ProjectPart::CXX14;
226
    part->qtVersion = ProjectPart::Qt5;
227
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
228 229 230
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath)
            << HeaderPath(testDataDir.frameworksDir(false), HeaderPath::FrameworkPath);
231
    const QString &source = testDataDir.fileFromSourcesDir(
232
        _("test_modelmanager_framework_headers.cpp"));
233
    part->files << ProjectFile(source, ProjectFile::CXXSource);
234
    pi.appendProjectPart(part);
235
    pi.finish();
236

237
    mm->updateProjectInfo(pi).waitForFinished();
238 239
    QCoreApplication::processEvents();

240
    QVERIFY(mm->snapshot().contains(source));
241
    Document::Ptr doc = mm->document(source);
242 243 244 245 246 247 248 249 250 251 252 253 254 255
    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"));
    }
}
256 257

/// QTCREATORBUG-9056
258 259 260
/// 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()
261 262 263 264
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

265
    const MyTestDataDir testDataDir(_("testdata"));
266

267 268
    const QString testCpp(testDataDir.fileFromSourcesDir(_("test_modelmanager_refresh.cpp")));
    const QString testHeader(testDataDir.fileFromSourcesDir( _("test_modelmanager_refresh.h")));
269

270
    Project *project = helper.createProject(
271
                _("test_modelmanager_refresh_also_includes_of_project_files"));
272
    ProjectInfo pi = ProjectInfo(project);
273

274 275
    typedef ProjectPart::HeaderPath HeaderPath;

276
    ProjectPart::Ptr part(new ProjectPart);
277
    part->languageVersion = ProjectPart::CXX14;
278
    part->qtVersion = ProjectPart::Qt5;
279
    part->projectDefines = QByteArray("#define OH_BEHAVE -1\n");
280 281
    part->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDir.includeDir(false), HeaderPath::IncludePath);
282
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
283
    pi.appendProjectPart(part);
284
    pi.finish();
285

286
    QSet<QString> refreshedFiles = updateProjectInfo(mm, &helper, pi);
287 288 289 290 291 292
    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    CPlusPlus::Snapshot snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));

293 294 295 296
    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");
297

298
    // Introduce a define that will enable another define once the document is reparsed.
299
    part->projectDefines = QByteArray("#define TEST_DEFINE 1\n");
300
    pi = ProjectInfo(project);
301
    pi.appendProjectPart(part);
302
    pi.finish();
303

304
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
305 306 307 308 309 310

    QCOMPARE(refreshedFiles.size(), 1);
    QVERIFY(refreshedFiles.contains(testCpp));
    snapshot = mm->snapshot();
    QVERIFY(snapshot.contains(testHeader));
    QVERIFY(snapshot.contains(testCpp));
311 312 313 314 315 316

    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");
317
}
318 319

/// QTCREATORBUG-9205
320
/// Check: When reparsing the same files again, no errors occur
321
///        (The CppSourceProcessor's already seen files are properly cleared!).
322
void CppToolsPlugin::test_modelmanager_refresh_several_times()
323 324 325 326
{
    ModelManagerTestHelper helper;
    CppModelManager *mm = CppModelManager::instance();

327
    const MyTestDataDir testDataDir(_("testdata_refresh"));
328

329 330 331
    const QString testHeader1(testDataDir.file(_("defines.h")));
    const QString testHeader2(testDataDir.file(_("header.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
332

333
    Project *project = helper.createProject(_("test_modelmanager_refresh_several_times"));
334
    ProjectInfo pi = ProjectInfo(project);
335 336

    ProjectPart::Ptr part(new ProjectPart);
337
    part->languageVersion = ProjectPart::CXX14;
338 339 340 341
    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));
342
    pi.appendProjectPart(part);
343
    pi.finish();
344 345 346
    mm->updateProjectInfo(pi);

    CPlusPlus::Snapshot snapshot;
347
    QSet<QString> refreshedFiles;
348 349
    CPlusPlus::Document::Ptr document;

350
    QByteArray defines = "#define FIRST_DEFINE";
351
    for (int i = 0; i < 2; ++i) {
352
        pi = ProjectInfo(project);
353 354 355
        ProjectPart::Ptr part(new ProjectPart);
        // Simulate project configuration change by having different defines each time.
        defines += "\n#define ANOTHER_DEFINE";
356
        part->projectDefines = defines;
357
        part->languageVersion = ProjectPart::CXX14;
358 359 360 361 362
        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);
363
        pi.finish();
364

365
        refreshedFiles = updateProjectInfo(mm, &helper, pi);
366
        QCOMPARE(refreshedFiles.size(), 3);
367

368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        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());
    }
}
388

389 390 391 392 393 394 395
/// 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();

396 397
    const MyTestDataDir testDataDir(_("testdata_refresh"));
    const QString testCpp(testDataDir.file(_("source.cpp")));
398

399
    Project *project = helper.createProject(_("test_modelmanager_refresh_2"));
400
    ProjectInfo pi = ProjectInfo(project);
401 402

    ProjectPart::Ptr part(new ProjectPart);
403
    part->languageVersion = ProjectPart::CXX14;
404 405 406
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    pi.appendProjectPart(part);
407
    pi.finish();
408 409

    // Reindexing triggers a reparsing thread
410
    helper.resetRefreshedSourceFiles();
411 412
    QFuture<void> firstFuture = mm->updateProjectInfo(pi);
    QVERIFY(firstFuture.isStarted() || firstFuture.isRunning());
413
    firstFuture.waitForFinished();
414
    const QSet<QString> refreshedFiles = helper.waitForRefreshedSourceFiles();
415 416 417 418 419 420 421 422
    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());
}

423 424 425 426 427 428 429
/// 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();

430
    const MyTestDataDir testDataDir(_("testdata_refresh"));
431

432 433 434
    const QString testHeader1(testDataDir.file(_("header.h")));
    const QString testHeader2(testDataDir.file(_("defines.h")));
    const QString testCpp(testDataDir.file(_("source.cpp")));
435

436
    Project *project = helper.createProject(_("test_modelmanager_refresh_3"));
437
    ProjectInfo pi = ProjectInfo(project);
438 439

    ProjectPart::Ptr part(new ProjectPart);
440
    part->languageVersion = ProjectPart::CXX14;
441 442 443 444
    part->qtVersion = ProjectPart::Qt5;
    part->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    part->files.append(ProjectFile(testHeader1, ProjectFile::CXXHeader));
    pi.appendProjectPart(part);
445
    pi.finish();
446 447

    CPlusPlus::Snapshot snapshot;
448
    QSet<QString> refreshedFiles;
449

450
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
451 452 453 454 455 456 457 458 459 460

    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
461
    pi = ProjectInfo(project);
462
    ProjectPart::Ptr newPart(new ProjectPart);
463
    newPart->languageVersion = ProjectPart::CXX14;
464 465 466 467
    newPart->qtVersion = ProjectPart::Qt5;
    newPart->files.append(ProjectFile(testCpp, ProjectFile::CXXSource));
    newPart->files.append(ProjectFile(testHeader2, ProjectFile::CXXHeader));
    pi.appendProjectPart(newPart);
468
    pi.finish();
469

470
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    // 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);
488 489 490 491 492 493 494 495
    QFETCH(QStringList, initialProjectFiles);
    QFETCH(QStringList, finalProjectFiles);

    Tests::TemporaryCopiedDir temporaryDir(
                MyTestDataDir(QLatin1String("testdata_refresh2")).path());
    fileToChange = temporaryDir.absolutePath(fileToChange.toUtf8());
    initialProjectFiles = toAbsolutePaths(initialProjectFiles, temporaryDir);
    finalProjectFiles = toAbsolutePaths(finalProjectFiles, temporaryDir);
496 497 498 499

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

500
    Project *project = helper.createProject(_("test_modelmanager_refresh_timeStampModified"));
501
    ProjectInfo pi = ProjectInfo(project);
502 503

    ProjectPart::Ptr part(new ProjectPart);
504
    part->languageVersion = ProjectPart::CXX14;
505
    part->qtVersion = ProjectPart::Qt5;
506 507
    foreach (const QString &file, initialProjectFiles)
        part->files.append(ProjectFile(file, ProjectFile::CXXSource));
508
    pi = ProjectInfo(project);
509
    pi.appendProjectPart(part);
510
    pi.finish();
511 512 513

    Document::Ptr document;
    CPlusPlus::Snapshot snapshot;
514
    QSet<QString> refreshedFiles;
515

516
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
517 518 519

    QCOMPARE(refreshedFiles.size(), initialProjectFiles.size());
    snapshot = mm->snapshot();
520 521 522
    foreach (const QString &file, initialProjectFiles) {
        QVERIFY(refreshedFiles.contains(file));
        QVERIFY(snapshot.contains(file));
523 524 525 526 527 528 529 530 531 532 533 534 535
    }

    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;";
536
    QVERIFY(fileChangerAndRestorer.writeContents(newFileContentes));
537 538 539

    // Add or remove source file. The configuration stays the same.
    part->files.clear();
540 541
    foreach (const QString &file, finalProjectFiles)
        part->files.append(ProjectFile(file, ProjectFile::CXXSource));
542
    pi = ProjectInfo(project);
543
    pi.appendProjectPart(part);
544
    pi.finish();
545

546
    refreshedFiles = updateProjectInfo(mm, &helper, pi);
547 548 549

    QCOMPARE(refreshedFiles.size(), finalProjectFiles.size());
    snapshot = mm->snapshot();
550 551 552
    foreach (const QString &file, finalProjectFiles) {
        QVERIFY(refreshedFiles.contains(file));
        QVERIFY(snapshot.contains(file));
553 554 555 556 557 558 559 560 561 562 563 564
    }
    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");
565 566
    QTest::addColumn<QStringList>("initialProjectFiles");
    QTest::addColumn<QStringList>("finalProjectFiles");
567

568 569
    const QString testCpp = QLatin1String("source.cpp");
    const QString testCpp2 = QLatin1String("source2.cpp");
570 571

    const QString fileToChange = testCpp;
572 573
    const QStringList projectFiles1 = QStringList() << testCpp;
    const QStringList projectFiles2 = QStringList() << testCpp << testCpp2;
574 575 576 577 578 579 580 581

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

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

582 583
/// Check: If a second project is opened, the code model is still aware of
///        files of the first project.
584 585
void CppToolsPlugin::test_modelmanager_snapshot_after_two_projects()
{
586
    QSet<QString> refreshedFiles;
587 588 589 590 591 592
    ModelManagerTestHelper helper;
    ProjectCreator project1(&helper);
    ProjectCreator project2(&helper);
    CppModelManager *mm = CppModelManager::instance();

    // Project 1
593 594 595 596 597
    project1.create(_("test_modelmanager_snapshot_after_two_projects.1"),
                    _("testdata_project1"),
                    QStringList() << _("foo.h")
                                  << _("foo.cpp")
                                  << _("main.cpp"));
598

599
    refreshedFiles = updateProjectInfo(mm, &helper, project1.projectInfo);
600
    QCOMPARE(refreshedFiles, project1.projectFiles.toSet());
601 602 603 604 605 606
    const int snapshotSizeAfterProject1 = mm->snapshot().size();

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

    // Project 2
607 608 609 610 611
    project2.create(_("test_modelmanager_snapshot_after_two_projects.2"),
                    _("testdata_project2"),
                    QStringList() << _("bar.h")
                                  << _("bar.cpp")
                                  << _("main.cpp"));
612

613
    refreshedFiles = updateProjectInfo(mm, &helper, project2.projectInfo);
614
    QCOMPARE(refreshedFiles, project2.projectFiles.toSet());
615 616 617 618 619 620 621 622 623 624

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

626 627
/// Check: (1) For a project with a *.ui file an AbstractEditorSupport object
///            is added for the ui_* file.
628
/// Check: (2) The CppSourceProcessor can successfully resolve the ui_* file
629
///            though it might not be actually generated in the build dir.
630 631
///

632 633
void CppToolsPlugin::test_modelmanager_extraeditorsupport_uiFiles()
{
634
    VerifyCleanCppModelManager verify;
635

636 637 638
    TemporaryCopiedDir temporaryDir(MyTestDataDir(QLatin1String("testdata_guiproject1")).path());
    QVERIFY(temporaryDir.isValid());
    const QString projectFile = temporaryDir.absolutePath("testdata_guiproject1.pro");
639

640
    ProjectOpenerAndCloser projects;
641 642
    ProjectInfo projectInfo = projects.open(projectFile, /*configureAsExampleProject=*/ true);
    QVERIFY(projectInfo.isValid());
643 644 645

    // Check working copy.
    // An AbstractEditorSupport object should have been added for the ui_* file.
646
    CppModelManager *mm = CppModelManager::instance();
647
    WorkingCopy workingCopy = mm->workingCopy();
648 649 650 651

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

    QStringList fileNamesInWorkinCopy;
652
    QHashIterator<Utils::FileName, QPair<QByteArray, unsigned> > it = workingCopy.iterator();
653 654
    while (it.hasNext()) {
        it.next();
655
        fileNamesInWorkinCopy << Utils::FileName::fromString(it.key().toString()).fileName();
656 657
    }
    fileNamesInWorkinCopy.sort();
658
    const QString expectedUiHeaderFileName = _("ui_mainwindow.h");
659 660 661
    QCOMPARE(fileNamesInWorkinCopy.at(0), mm->configurationFileName());
    QCOMPARE(fileNamesInWorkinCopy.at(1), expectedUiHeaderFileName);

662 663
    // Check CppSourceProcessor / includes.
    // The CppSourceProcessor is expected to find the ui_* file in the working copy.
664
    const QString fileIncludingTheUiFile = temporaryDir.absolutePath("mainwindow.cpp");
665 666 667 668 669 670 671 672
    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);
673 674
    QCOMPARE(Utils::FileName::fromString(includedFiles.at(0)).fileName(), _("mainwindow.h"));
    QCOMPARE(Utils::FileName::fromString(includedFiles.at(1)).fileName(), _("ui_mainwindow.h"));
675
}
676 677 678 679 680

/// 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()
{
681 682
    ModelManagerTestHelper helper;

683 684
    MyTestDataDir testDataDirectory(_("testdata_guiproject1"));
    const QString file = testDataDirectory.file(_("main.cpp"));
685 686

    CppModelManager *mm = CppModelManager::instance();
687
    helper.resetRefreshedSourceFiles();
688 689

    // Open a file in the editor
hjk's avatar
hjk committed
690
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 0);
691
    Core::IEditor *editor = Core::EditorManager::openEditor(file);
692
    QVERIFY(editor);
hjk's avatar
hjk committed
693
    QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
694 695 696
    QVERIFY(mm->isCppEditor(editor));
    QVERIFY(mm->workingCopy().contains(file));

697 698
    // Wait until the file is refreshed
    helper.waitForRefreshedSourceFiles();
699 700

    // Close file/editor
701
    Core::EditorManager::closeDocument(editor->document(), /*askAboutModifiedEditors=*/ false);
702
    helper.waitForFinishedGc();
703 704 705 706 707

    // Check: File is removed from the snapshpt
    QVERIFY(!mm->workingCopy().contains(file));
    QVERIFY(!mm->snapshot().contains(file));
}
708 709 710 711 712 713

/// Check: Files that are open in the editor are not garbage collected.
void CppToolsPlugin::test_modelmanager_dont_gc_opened_files()
{
    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
    QVERIFY(mm->isCppEditor(editor));

727 728
    // Wait until the file is refreshed and check whether it is in the working copy
    helper.waitForRefreshedSourceFiles();
729

730 731 732 733 734 735 736 737 738 739
    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
740
    Core::EditorManager::closeDocument(editor->document());
741 742 743
    helper.waitForFinishedGc();
    QVERIFY(mm->snapshot().isEmpty());
}
744 745 746 747 748 749 750

namespace {
struct EditorCloser {
    Core::IEditor *editor;
    EditorCloser(Core::IEditor *editor): editor(editor) {}
    ~EditorCloser()
    {
751
        using namespace CppTools;
752
        if (editor)
753
            QVERIFY(Tests::TestCase::closeEditorWithoutGarbageCollectorInvocation(editor));
754 755
    }
};
756 757 758 759 760 761 762 763

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())
764
                        return QString::fromUtf8(identifier->chars(), identifier->size());
765 766 767 768 769 770
                }
            }
        }
    }
    return QString();
}
771 772 773 774 775 776
}

void CppToolsPlugin::test_modelmanager_defines_per_project()
{
    ModelManagerTestHelper helper;

777 778 779 780
    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"));
781 782 783

    CppModelManager *mm = CppModelManager::instance();

784
    Project *project = helper.createProject(_("test_modelmanager_defines_per_project"));
785

786 787
    typedef ProjectPart::HeaderPath HeaderPath;

788
    ProjectPart::Ptr part1(new ProjectPart);
789
    part1->projectFile = QLatin1String("project1.projectfile");
790 791
    part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource));
    part1->files.append(ProjectFile(header, ProjectFile::CXXHeader));
792
    part1->languageVersion = ProjectPart::CXX11;
793
    part1->qtVersion = ProjectPart::NoQt;
794
    part1->projectDefines = QByteArray("#define SUB1\n");
795 796
    part1->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
797 798

    ProjectPart::Ptr part2(new ProjectPart);
799
    part2->projectFile = QLatin1String("project1.projectfile");
800 801
    part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource));
    part2->files.append(ProjectFile(header, ProjectFile::CXXHeader));
802
    part2->languageVersion = ProjectPart::CXX11;
803
    part2->qtVersion = ProjectPart::NoQt;
804
    part2->projectDefines = QByteArray("#define SUB2\n");
805 806
    part2->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
807

808
    ProjectInfo pi = ProjectInfo(project);
809 810
    pi.appendProjectPart(part1);
    pi.appendProjectPart(part2);
811
    pi.finish();
812

813
    updateProjectInfo(mm, &helper, pi);
814 815 816
    QCOMPARE(mm->snapshot().size(), 4);

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

819 820 821 822 823 824 825 826 827 828 829 830 831
    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);
832 833
        EditorCloser closer(editor);
        QVERIFY(editor);
hjk's avatar
hjk committed
834
        QCOMPARE(Core::DocumentModel::openedDocuments().size(), 1);
835 836
        QVERIFY(mm->isCppEditor(editor));

837
        Document::Ptr doc = mm->document(fileName);
838
        QCOMPARE(nameOfFirstDeclaration(doc), firstDeclarationName);
839 840
    }
}
841

842
void CppToolsPlugin::test_modelmanager_precompiled_headers()
843 844 845
{
    ModelManagerTestHelper helper;

846 847 848 849 850 851
    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"));
    const QString pch1File = testDataDirectory.file(_("pch1.h"));
    const QString pch2File = testDataDirectory.file(_("pch2.h"));
852 853 854

    CppModelManager *mm = CppModelManager::instance();

855
    Project *project = helper.createProject(_("test_modelmanager_defines_per_project_pch"));
856

857 858
    typedef ProjectPart::HeaderPath HeaderPath;

859
    ProjectPart::Ptr part1(new ProjectPart);
860
    part1->projectFile = QLatin1String("project1.projectfile");
861 862
    part1->files.append(ProjectFile(main1File, ProjectFile::CXXSource));
    part1->files.append(ProjectFile(header, ProjectFile::CXXHeader));
863
    part1->languageVersion = ProjectPart::CXX11;
864 865
    part1->qtVersion = ProjectPart::NoQt;
    part1->precompiledHeaders.append(pch1File);
866 867
    part1->headerPaths = QList<HeaderPath>()
            << HeaderPath(testDataDirectory.includeDir(false), HeaderPath::IncludePath);
868 869

    ProjectPart::Ptr part2(new ProjectPart);
870
    part2->projectFile = QLatin1String("project2.projectfile");
871 872
    part2->files.append(ProjectFile(main2File, ProjectFile::CXXSource));
    part2->files.append(ProjectFile(header, ProjectFile::CXXHeader));
873
    part2->languageVersion = ProjectPart::CXX11;